标签:
题目: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
".
解析:将字符串中的单词逆序输出
借助一个堆栈,从前向后遍历字符串,遇到空,跳过,直到非空字符,拼接word,等再次遇到空时,得到一个word,加入堆栈,
以此类推,直到遍历到s的最后一个字符为止。
最后,将堆栈中的word依次输出
java编码:
方法一:
public String reverseWords(String s) {
if(s == null || s.length() == 0)
return s;
int index = 0; //the pointer to traverse
int len = s.length();
Stack<String> stack = new Stack<String>(); //堆栈,先进后出,顺序存入单词,逆序输出
StringBuilder sBuilder = new StringBuilder(); //记录每一个单词
char[] characters = s.toCharArray();
while(index < len){ //遍历字符串
for(;index < len && characters[index] == ‘ ‘; ++index);//跳过空字符
for(;index < len && characters[index] != ‘ ‘; ++index){//拼接word
sBuilder.append(characters[index]);
}
if(sBuilder.length() > 0){//将有效的word压入堆栈
stack.push(sBuilder.toString());
sBuilder.delete(0,sBuilder.length());//清空stringbuilder
}
}
sBuilder.delete(0,sBuilder.length());//清空stringbuilder
while(stack.size() > 1){//非最后一个word,输出,加空格
sBuilder.append(stack.pop() + " ");
}
if(stack.size() == 1)//最后一个word,输出,不加空格,这里要判断stack是否为空,因为可能输入的字符串为空
sBuilder.append(stack.pop());
return sBuilder.toString();
}
方法二:
正则表达式,\s表示空格,+表示至少一个空格,这样就可以将多个空格分隔的word提取出来了
public String reverseWords(String s) { String[] words = s.split("\\s+"); // regular expression StringBuffer sb = new StringBuffer(); for(int i = words.length - 1; i >= 0; --i){ sb.append(words[i] + " "); } return sb.toString().trim(); }
reverse words in a string(java 注意一些细节处理)
标签:
原文地址:http://www.cnblogs.com/mydesky2012/p/5723953.html