557. Reverse Words in a String III

Description:

https://leetcode.com/submissions/detail/105718837/

Boundary:

No boundary needs to be considered.

Algorithm:

Use a for loop to read the char in the string one by one, record the start and end of each word.

If meets a ‘ ‘, swap poistion and store in an new string.

Code:

class Solution {
public:
string reverseWords(string s) {
string s_new = s;
int counter = 0;
int start = 0;
for (int k = 0; k < s.size();k++)
{
if (s[k] == ‘ ‘)
{
for (int i = start; i < counter; i++)
{
char s1 = s[counter – 1 – (i – start)];
s_new[i] = s1;
}

start = counter + 1;
}
else if (k == s.size() – 1)
{
for (int i = start; i <= counter; i++)
{
char s1 = s[counter – (i – start)];
s_new[i] = s1;
}
}
counter++;
}
return s_new;
}
};

Leave a Reply

Your email address will not be published. Required fields are marked *