151. Reverse Words in a String (快慢指针)
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue
", Output: "blue is sky the
".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
class Solution: def reverseWords(self, s: str) -> str: def reverse(word): word = list(word) n = len(word) for i in range((n//2)): word[i],word[n-i-1] = word[n-i-1],word[i] return ''.join(word) s = reverse(s.strip()) return ' '.join([reverse(w) for w in s.split()])
/* * @lc app=leetcode.cn id=151 lang=cpp * * [151] 反转字符串中的单词 */ // @lc code=start class Solution { public: void reverse(string& s, int ss, int e) { int start = ss; int end = e; while(start<end) { char tt = s[start]; s[start] = s[end]; s[end] = tt; start++; end--; } } string reverseWords(string s) { // del space int a = 0; for(int i = 0;i < s.size();i++) { if ((s[i] != ' ') || (s[i] == ' ' && i-1>=0 && s[i-1] !=' ')) { s[a] = s[i]; a++; } } // del last space if (s[a-1] == ' ') { s.resize(a-1); } else { s.resize(a); } reverse(s,0,s.size()-1); int k = 0; for(int i = 0; i < s.size(); i++) { if (s[i]==' ') { reverse(s,k,i-1); k = i+1; } } // reverse last word reverse(s,k,s.size()-1); return s; } }; // @lc code=end
class Solution { public: //[] void reverse(string& s, int start, int end) { int i = start,j = end; while(i<j) { char tt = s[i]; s[i] = s[j]; s[j] = tt; i++;j--; } } string reverseWords(string s) { // 删除空格 int a = 0; for(int j = 0;j < s.size();j++) { if (s[j]!=' ') { if (a!=0) s[a++] = ' '; while(j < s.size() && s[j]!=' ') s[a++] = s[j++]; } } s.resize(a); // 先整体反转字符串 reverse(s,0,s.size()-1); int i = 0; // 每个字符串再反转 for(int j = 0;j < s.size();j++) { if (s[j]==' ') { reverse(s,i,j-1); i = j+1; } } reverse(s,i,s.size()-1); return s; } };
1 class Solution(object): 2 def reverseWords(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 return ' '.join(s.strip().split()[::-1])