首页 > 代码库 > [LeetCode]Reverse Words in a String

[LeetCode]Reverse Words in a String

题目:给定一个字符串数组,翻转数组中的单词,样例:the sky is blue  输出  blue is sky the

算法:字符串处理,要注意一些细节: 

1. 字符串为空 

2. 字符串由空白组成

3. 字符串前度和后度空白

4. 字符串之间充满了空白

public class Solution {
    public String reverseWords(String s) {
	        if (null == s) {
	        	// case when s is null
	        	return null;
	        }
	        
	        int length = s.length();
	        ArrayList<String> words = new ArrayList<String>();
	        for (int i=0; i<length; ) {
	        	String word = new String();
	        	while (i<length && (' '==s.charAt(i) || '\t'==s.charAt(i))) {
	        		++i;
	        	}
	        	while (i<length && ' '!=s.charAt(i) && '\t'!=s.charAt(i)) {
	        		word += s.charAt(i++);
	        	}
	        	if (word.length() >= 1) {
	        		words.add(word);
	        	}
	        }
	        if (words.isEmpty()) {
	        	return "";
	        } else {
	        	String reverse = new String();
	        	boolean isFirstWord = true;
	        	int nWords = words.size();
	        	for (int j=nWords-1; j>=0; --j) {
	        		if (isFirstWord) {
		        		reverse += words.get(j);
		        		isFirstWord = false;
		        	} else {
		        		reverse += (" " + words.get(j));
		        	}
	        	}
	        	return reverse;
	        }
	    }
}