[LeetCode] 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
".
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.
这题刚看时觉得挺简单的,想了想发现这尼玛体力题啊,主要是处理连续空字符的需要注意一下.
public class Solution { public String reverseWords( String s ) { char[] chs = s.toCharArray(); if( s.length() == 1 && s.charAt( 0 ) == ' ' ) return new String(); int start = 0; int empty = 0; int end0 = 0; for( int i = 0; i < s.length(); i++ ) { if( s.charAt( i ) != ' ' ) { start = i; break; } else { empty++; } } for( int i = s.length() - 1; i >= 0; i-- ) { if( s.charAt( i ) == ' ' ) { end0++; }else{ break; } } if( empty == s.length() ) return new String(); s = new String( s.toCharArray(), start,s.length()-start-end0 ); int l = 0; int r = s.length() - 1; chs = s.toCharArray(); while( l < r ) { char temp = chs[ l ]; chs[ l ] = chs[ r ]; chs[ r ] = temp; l++; r--; } l = 0; r = s.length() - 1; int c = 0; for( int i = 0; i < r; i++ ) { if( chs[ i ] == ' ' && chs[ i + 1 ] == ' ' ) { for( int j = i; j < r; j++ ) { chs[ j ] = chs[ j + 1 ]; } r--; i--; } } while( l <= r ) { if( chs[ l ] == ' ' || l == r ) { int end = l - ( l == r ? 0 : 1 ); while( c < end ) { char temp = chs[ c ]; chs[ c ] = chs[ end ]; chs[ end ] = temp; c++; end--; } l++; c = l; } else { l++; } } String ret = new String( chs, 0, r + 1 ); return ret; } public static void main( String[] args ) { Solution s = new Solution(); System.out.println( s.reverseWords( " a b " )); } }