Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note:In the string, each word is separated by single space and there will not be any extra space in the string.
思路:找到空格(或者末尾,此时无空格),对范围内的单次进行reverse,先入后出,想到stack。
知识点:string和stack的使用
http://www.cplusplus.com/reference/stack/stack/
http://www.cplusplus.com/reference/string/string/
代码1:
class Solution {
public:
string reverseWords(string s) {
for (int i = 0; i < s.length(); i++) {
if (s[i] != ' ') { // when i is a non-space
int j = i;
for (; j < s.length() && s[j] != ' '; j++) { } // move j to the next space
reverse(s.begin() + i, s.begin() + j);
i = j - 1;
}
}
return s;
}
};
代码2:
class Solution {
public:
string reverseWords(string s) {
stack<char> st;
string res;
st.push(' ');
for(char ch:s){
if(ch==' '){
while(st.size()>0){
char temp;
temp=st.top();
st.pop();
res.push_back(temp);
}
st.push(' ');
}
else{st.push(ch);}
}
//最后一次无空格,所以得单独处理
while(st.size()>1){
char temp;
temp=st.top();
st.pop();
res.push_back(temp);
}
return res;
}
};
代码3:
class Solution {
public:
string reverseWords(string s)
{
int spaceIdx = -1;
const int n = s.size();
for (int i = 0; i < n; i++)
{
if (s[i] == ' ' || i == n - 1)
{
if (i == n - 1)
i++;
int l = spaceIdx + 1;
int r = i - 1;
while (l < r)
swap(s[l++], s[r--]);
spaceIdx = i;
}
}
return s;
}
};
头文件:<utility>