For example,
Given s = "the sky is blue",
return "blue is sky the".
初步:
package leetcode20150616;
/*
* Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
思路:
1:既然字符串要按照某一種順序顯示,顯然是要把各個部分分割開,正好String 函數中有一個split()
函數,這樣就可以完成一個分割
2:分割之後的字符串保存在一個數組當中,這樣具體按照要求的順序顯示就可以了!
按照如上思路很快解決了問題,看似解決了問題,但是很多細節都沒有考慮,譬如:
1:輸入的字符串前後都有空格怎麼辦?
2:兩個單詞之間有多個空格如何顯示?
*/
public class ReverseString {
public String ReverStr(String givStr) {
String [] arrString = givStr.split(" ");
String returnString = "";
int length = arrString.length;
for(int i=length-1; i>=0; i--) {
returnString += arrString[i]+" ";
}
return returnString;
}
public static void main(String [] args) {
ReverseString rs = new ReverseString();
String returnString = rs.ReverStr("I love U");
System.out.println(returnString);
}
}
按照如上思路很快解決了問題,看似解決了問題,但是很多細節都沒有考慮,譬如:
1:輸入的字符串前後都有空格怎麼辦?
2:兩個單詞之間有多個空格如何顯示?
<pre name="code" class="java">package leetcode20150616;
/*
* Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
思路:
1:既然字符串要按照某一種順序顯示,顯然是要把各個部分分割開,正好String 函數中有一個split()
函數,這樣就可以完成一個分割
2:分割之後的字符串保存在一個數組當中,這樣具體按照要求的順序顯示就可以了!
按照如上思路很快解決了問題,看似解決了問題,但是很多細節都沒有考慮,譬如:
1:輸入的字符串前後都有空格怎麼辦?
2:兩個單詞之間有多個空格如何顯示?
*/
public class ReverseString {
public String ReverStr(String givStr) {
///將輸入的字符串先去掉前後多餘的空格
///兩個字符串中可能有多個空格,這樣用正則表達式來更合適
///正則表達式中\s代表任意的空白符,因爲寫在“”中,所以需要轉意\\s,+表示大於等於1個
String regex ="\\s+";
String [] arrString = givStr.trim().split(regex);
String returnString = "";
int length = arrString.length;
for(int i=length-1; i>=0; i--) {
returnString += arrString[i]+" ";
}
return returnString;
}
public static void main(String [] args) {
ReverseString rs = new ReverseString();
String returnString = rs.ReverStr(" I love U ");
System.out.println(returnString);
}
}
這樣就Ok了
同時看了一下這位兄弟的解決方法http://blog.csdn.net/bruce_6/article/details/40044483