标签:ever nbsp har output note div bsp 解题思路 trail
算法描述:
Given an input string, reverse the string word by word.
Example:
Input: "the sky is blue
", Output: "blue is sky the
".
Note:
Follow up: For C programmers, try to solve it in-place in O(1) space.
解题思路:先逐词翻转,再整句翻转。注意去除空格。
void reverseWords(string &s, int i, int j){ while(i < j){ char temp = s[i]; s[i++]=s[j]; s[j--]=temp; } } void reverseWords(string &s){ int i = 0; int j = 0; int l = 0; int n = s.size(); int count = 0; while(true){ while(i < n && s[i] == ‘ ‘) i++; if(i==n) break; if(count) s[j++] = ‘ ‘; l=j; while(i < n && s[i]!= ‘ ‘) {s[j]=s[i]; j++; i++;} reverseWords(s,l,j-1); count++; } s.resize(j); reverseWords(s,0,j-1); }
LeetCode-151-Reverse Words in s String
标签:ever nbsp har output note div bsp 解题思路 trail
原文地址:https://www.cnblogs.com/nobodywang/p/10354474.html