151. Reverse Words in a String(java 注意细节处理)

题目: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.isEmpty()){//输出,空格分隔
sBuilder.append(stack.pop() + " ");
}
return sBuilder.toString().trim();
}

方法二:

正则表达式,\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(); //trim是去除字符串的首尾空格
}
上一篇:c#窗体移动与窗体阴影效果


下一篇:eschop购物实现立即购买和加入购物车