Reverse Words in a String
源自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".
目前被接受的Java代码如下:
public class Solution {
public String reverseWords(String s) {
//delete spaces before and after string
String tmp = s.trim();
//if no space exists, return original string
if(s.indexOf(" ") == -1)
{
return s;
}
//if only spaces exist, return ""
if(tmp == "")
{
return tmp;
}
//construct a string array has spaceCount+1 elements to store string elements
String[] strArray = tmp.split("\\s+");
//construct final string in reverse sequence
StringBuilder result = new StringBuilder();
result.append(strArray[strArray.length-1].trim());
for(int i = strArray.length-2; i >= 0; i--)
{
if(strArray[i] != null)
{
result.append(" " + strArray[i]);
}
}
return result.toString();
}
}
其中有几个关键问题要注意:
1. 如果s全是空格的情况下,经过trim之后应该是"",此时不应该返回s,而应该返回“”;也就是说很容易遗漏tmp == ""的情况;
2. 在String类中的split函数中,参数\\s表示空格、回车、换行等空白符;+号表示一个或多个;因此根据多个空格符拆分字符串需要用到\\s+;
3. StringBuilder类的append函数相比String类的+ operator效率高很多;
4. 先append最后一个单词,然后开始循环append空格和接下来的单词;
5. 切记toString();
主要用到的String类函数有trim(), indexOf(), split()。split函数需要用到正则表达式,用到的时候再深入学习。
浙公网安备 33010602011771号