Skip to content

Latest commit

 

History

History
77 lines (61 loc) · 1.82 KB

151.ReverseWordsInString.md

File metadata and controls

77 lines (61 loc) · 1.82 KB

tags: String

#[LeetCode 151] Reverse Words in a String

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.

click to show clarification.

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.

Diffculty
Hard

Similar Problems
[LeetCode ] Reverse Words in a String II Medium

Analysis

思路: 从后往前遍历,取出每个单词翻转后,append到新的数组

class Solution { public: string reverseWords(string s) { if (s.empty()) return s; string s_ret, s_temp; string::size_type ix = s.size(); while (ix != 0) { s_temp.clear(); while (!isspace(s[--ix])) { s_temp.push_back(s[ix]); if (ix == 0) break; } if (!s_temp.empty()) { if (!s_ret.empty()) s_ret.push_back(' '); std::reverse(s_temp.begin(), s_temp.end()); s_ret.append(s_temp); } } return s_ret; } };

// 一遍扫描 class Solution { public: void reverseWords(string &s) { string ret; int j = s.size(); for(int i=s.size()-1; i>=0; i--) { if(s[i]==' ') j = i; else if(i==0 || s[i-1]==' ') { if(!ret.empty()) ret.append(" "); ret.append(s.substr(i, j-i)); } } s = ret; } };