Reverse Words in a String[LeetCode]
2014-03-15 13:02
417 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
LeetCode上第一题,没注意Clarification,浪费了些时间:各种“
” “ a ” “ a” “a ” “ a ” "
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
LeetCode上第一题,没注意Clarification,浪费了些时间:各种“
” “ a ” “ a” “a ” “ a ” "
the sky is blue"等都需要考虑
void reverseWords(string &s) { if(s == "")return; string s1 = ""; string temp = ""; size_t i = 0; //去掉前面的空格 while(s[i] == ' ')i++; while(i < s.length()){ if(s[i] != ' '){ temp += s[i]; }else{ if(s1 == ""){ s1 = temp; temp = ""; }else{ if(temp!= "") s1 = temp + " " + s1; temp = ""; } } i++; } if(temp != ""){ if(s1 != ""){ s1 = temp + " " + s1; }else{ s1 = temp; } } s = s1; }
相关文章推荐
- 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:Reverse Words in a String
- LeetCode之Reverse Words in a String III
- [LeetCode]Reverse Words in a String
- LeetCode: Reverse Words in a String && Rotate Array
- LeetCode 557 Reverse Words in a String III(逆转字符串)
- [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】Reverse Words in a String
- 【LeetCode刷题Java版】Reverse Words in a String
- 字符串-leetcode 557 Reverse Words in a String III
- Leetcode: Reverse Words in a String
- LeetCode: Reverse Words in a String
- LeetCode-Reverse Words in a String