Reverse Words in a String--not finished yet
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Reverse Words in a String--not finished yet相关的知识,希望对你有一定的参考价值。
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.
Analyse: For my first thought, I will reverse the string first, then every word in the string has been reversed. Then I find each word, and reverse them. Space complexity is O(1). Time complexity is O(1).
1 class Solution { 2 public: 3 void reverse(string& s, int start, int end){ 4 if(start >= end) return; 5 for(int i = start, j = end; i < j; i++, j--) 6 swap(s[i], s[j]); 7 } 8 9 10 void reverseWords(string& s) { 11 if(s.size() < 2) return; 12 13 //first inverse the string 14 //every word has been reversed 15 reverse(s, 0, s.size() - 1); 16 17 //for each word, reverse the word back 18 int start = 0; 19 for(int i = 0; i < s.size(); i++){ 20 while(s[i] != ‘ ‘) i++; 21 if(i >= s.size()) i = s.size(); 22 reverse(s, start, i - 1); 23 start = i + 1; 24 } 25 26 for(int i = 0; i < s.size(); i++) 27 cout<<s[i]; 28 29 } 30 };
以上是关于Reverse Words in a String--not finished yet的主要内容,如果未能解决你的问题,请参考以下文章
186. Reverse Words in a String II
LeetCode Reverse Words in a String III
4.Reverse Words in a String III
Reverse Words in a String leetcode