码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Reverse Words in a String

时间:2014-07-12 20:46:45      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   os   2014   

题目:给定一个字符串数组,翻转数组中的单词,样例: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;
	        }
	    }
}

[LeetCode]Reverse Words in a String,布布扣,bubuko.com

[LeetCode]Reverse Words in a String

标签:style   blog   java   color   os   2014   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/37699409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!