[leetcode]151. Reverse Words in a String
2017-05-26 11:45
405 查看
题目链接:https://leetcode.com/problems/reverse-words-in-a-string/#/description
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
class Solution {
public:
// function to reverse any part of string from i to j (just one word or entire string)
void reverseword(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++; // skip spaces in front of the word
if(i==len) break;
if(wordcount) s[j++]=' ';
l=j;
while(i<len && s[i] != ' ') {s[j++]=s[i++];}
reverseword(s,l,j-1); // reverse word in place
wordcount++;
}
s.resize(j); // resize result string
reverseword(s,0,j-1); // reverse whole string
}
};
Given an input string, reverse the string word by word.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
class Solution {
public:
// function to reverse any part of string from i to j (just one word or entire string)
void reverseword(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++; // skip spaces in front of the word
if(i==len) break;
if(wordcount) s[j++]=' ';
l=j;
while(i<len && s[i] != ' ') {s[j++]=s[i++];}
reverseword(s,l,j-1); // reverse word in place
wordcount++;
}
s.resize(j); // resize result string
reverseword(s,0,j-1); // reverse whole string
}
};
相关文章推荐
- leetcode 151. Reverse Words in a String
- leetcode-java-151. Reverse Words in a String
- Leetcode 151. Reverse Words in a String
- LeetCode *** 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- 【C语言】 LeetCode 151. Reverse Words in a String
- [leetcode]151. Reverse Words in a String@Java解题报告
- [Leetcode]151. Reverse Words in a String
- leetcode 151. Reverse Words in a String
- 151. Reverse Words in a String Leetcode Python
- Reverse Words in a String (LeetCode)
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- [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(151)Reverse Words in a String
- [leetCode]Reverse Words in a String
- [Leetcode Solution] Reverse Words in a String