Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
这样就Ok了
同时看了一下这位兄弟的解决方法http://blog.csdn.net/bruce_6/article/details/40044483
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