[LeetCode刷题记录]Reverse Words in a String
2015-04-08 12:58
302 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
思路:每次遇到空格把每个单词反转,然后把整个字符串反转。
边界条件注意:开始的多个空格跳过,结尾的多个空格删掉。单词中间间隔的多个空格变成一个。
建议实现,就是把处理空格的字符串从字符串开始重写,然后反转单词。
然后把字符串resize(),删掉多余的内容。
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
思路:每次遇到空格把每个单词反转,然后把整个字符串反转。
边界条件注意:开始的多个空格跳过,结尾的多个空格删掉。单词中间间隔的多个空格变成一个。
建议实现,就是把处理空格的字符串从字符串开始重写,然后反转单词。
然后把字符串resize(),删掉多余的内容。
class Solution { public: void reverse(string &s, int i, int j){ while(i<j){ char t=s[i]; s[i++]=s[j]; s[j--]=t; } } void reverseWords(string &s) { int i=0, j=0; int l=0; int len=s.length(); int wordcount=0; while(true){ while(i<len && s[i] == ' ') i++; // 跳过前面空格 if(i==len) break; if(wordcount) s[j++]=' '; //除了了第一个以外,其他情况后一位变空格 l=j; while(i<len && s[i] != ' ') {s[j]=s[i]; j++; i++;} //拷贝覆盖 reverse(s,l,j-1); // 反转每个单词 wordcount++; } s.resize(j); // resize result string reverse(s,0,j-1); // reverse whole string } };
相关文章推荐
- Leetcode 第151题 最新题解 Reverse Words in a String
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- LeetCode(151)Reverse Words in a String
- Leetcode: Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode with Python】 Reverse Words in a String
- [LeetCode]Reverse Words in a String
- leetcode Reverse Words in a String
- [leetcode]Reverse Words in a String
- Leetcode_Reverse-Words-in-a-String
- LeetCode | Reverse Words in a String
- Reverse Words in a String (LeetCode)
- [Leetcode Solution] Reverse Words in a String
- LeetCode151:Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [leetCode]Reverse Words in a String
- leetcode - Reverse Words in a String
- [LeetCode] Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String