Problem
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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
这题在不考虑multi space空格的情况下的思路:将string全部反转,然后将反转后的string words by words反转。 两次反转,in place操作。
如果考虑multi space,必须改变String,因为String对象本身是不可以改变的,所以要用StringBuilder来处理
思路:设置指针指向单词的最后一位,
另一个指针从字符串最后一位向前遍历,碰到空格,则将该单词向后遍历挨个添加至新string中。
public class Solution { /** * @param s : A string * @return : A string */ public String reverseWords(String s) { // write your code StringBuilder sb = new StringBuilder(); int end = s.length(); for (int i = s.length()-1; i >= -1; i--) { if (i == -1 || s.charAt(i) == ‘ ‘ ) { if (i + 1 < end) { if (sb.length() > 0) sb.append(" "); for (int j = i + 1; j < end; j++) { sb.append(s.charAt(j)); } } end = i; } } return sb.toString(); } }
时间: 2024-10-10 05:38:02