leetcode [151]Reverse Words in a String
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue" Output: "blue is sky the"
Example 2:
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
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) extra space.
题目大意:
给定一个字符串,将字符串中的各个单词进行翻转。单词中可能会有前导和后导空格,去除前导和后导空格,并且将字符串中多个空格转化为一个空格。
解法:
先将整个字符串进行翻转,再将其中以空格为分割的单词,一个一个进行翻转。注意特殊的情况,比如“ ”全为空格的字符串。
java:
class Solution {
public String reverseWords(String s) {
if(s.isEmpty()) return s;
String reverse=new StringBuilder(s).reverse().toString();
System.out.println(reverse);
StringBuilder res=new StringBuilder();
int i=0;
while(i<reverse.length()){
StringBuilder tmp=new StringBuilder();
while(i<reverse.length()&&reverse.charAt(i)==' ') i++;
if(i<reverse.length()) res.append(' ');
while(i<reverse.length()&&reverse.charAt(i)!=' ') tmp.append(reverse.charAt(i++));
if(tmp.length()>0) res.append(tmp.reverse());
}
return res.length()==0?"":res.toString().substring(1);
}
}

浙公网安备 33010602011771号