leetcode[186]Reverse Words in a String II
2015-02-10 16:25
399 查看
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "
return "
Could you do it in-place without allocating extra space?
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Could you do it in-place without allocating extra space?
class Solution { public: //无需额外空间开销 //反转整个字符串, 再反转每个单词 void reverseWords(string &s) { if(s.length()<1)return; int i=0,j=s.length()-1; //去开头结尾的空格 while(s[i]==' '&&i<s.length()) { i++; if(i==s.length()) { s=""; return; } } while(s[j]==' '&&j>=0) { j--; if(j<0) { s=""; return; } } if(j-i<0)return; //截取除去开头结尾空格后的部分,并将其反转 s=s.substr(i,j-i+1); reverse(s.begin(),s.end()); //对每个以空格隔开的单词再次反转 i=0,j=0; while(j<s.length()) { while(s[j]!=' '&&j<s.length())j++; reverse(s.begin()+i,s.begin()+j); int tmp=j; while(s[j]==' '&&j<s.length())j++; if(tmp+1<s.length())s.erase(s.begin()+tmp+1,s.begin()+j); //注意此时s的长度已经变短,下边需要减去相应差值 int shortL=j-tmp-1; j-=shortL; i=j; } return; } /** 需额外空间开销 void reverseWords(string &s) { if(s.empty())return; string tmp=""; string str=""; int i=0; while(i<s.length()) { while(s[i]==' '&&i<s.length())i++; if(s[i]!=' '&&i<s.length()) { while(s[i]!=' '&&i<s.length())tmp=s[i++]+tmp; str+=(tmp+' '); tmp=""; } } reverse(str.begin(),str.end()); int n=str[0]==' '?1:0; s=str.substr(n,str.size()); return; } */ };
相关文章推荐
- LeetCode LeetCode 186 - Reverse Words in a String II
- [LeetCode]186 Reverse Words in a String II
- [LeetCode186]Reverse Words in a String II
- LeetCode - Reverse Words in a String I && II
- [LeetCode] Reverse Words in a String II(in-place 算法)
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- leetcode_186_Reverse Words in a String
- Leetcode: Reverse Words in a String II
- LeetCode-Reverse Words in a String II
- Medium 186题 Reverse Words in a String II
- [Leetcode]Reverse Words in a String II
- leetcode Reverse Words in a String II
- Reverse Words in a String II -- LeetCode
- leetcode Reverse Words in a String II
- Leetcode Reverse Words in a String II
- [LeetCode] Reverse Words in a String II
- LeetCode Reverse Words in a String II
- 186. Reverse Words in a String II
- 【Leetcode】Reverse Words in a String II
- [LeetCode] Reverse Words in a String II