[LeetCode]Reverse Words in a String
2015-02-12 21:35
309 查看
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
这道题要求将一个字符串中的单词顺序反转,单词内部不反转,同时将单词间的多个空格合并成一个,头尾的空格删除。
思路:
1. 将整个字符串按照字母整个进行反转
2. 单词内进行反转,设置first和last分别表示单词的结束和开始,N个空格的第一个的前一个位置是单词的结尾,N个空格的最后一个的下一个是单词的开始。同时删去多余的空格。
3. 不额外使用存储空间。
下面贴上代码:
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
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.
这道题要求将一个字符串中的单词顺序反转,单词内部不反转,同时将单词间的多个空格合并成一个,头尾的空格删除。
思路:
1. 将整个字符串按照字母整个进行反转
2. 单词内进行反转,设置first和last分别表示单词的结束和开始,N个空格的第一个的前一个位置是单词的结尾,N个空格的最后一个的下一个是单词的开始。同时删去多余的空格。
3. 不额外使用存储空间。
下面贴上代码:
class Solution { public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int first=0; int last=0; int i = 0; while (first != s.length()){ while (first != s.length() && s[first] == ' ') first++; last = first; while (last != s.length() && s[last] != ' ') last++; if (i != 0 && first <= last - 1) s[i++] = ' '; for (int j = last - 1; first < j; first++, j--){ swap(s[j], s[first]); s[i++] = s[first]; } while (first < last){ s[i++] = s[first++]; } } s.resize(i); } };
相关文章推荐
- 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