问题如下
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
java程序如下:
package leetcode1.ReverseWordsinAString;
public class Solution {
public String reverseWords(String s){
String result = "";
String[] sArray = s.split(" ");
for(String str:sArray){
if (str.equals("") == false)
result = str + " " + result;
}
return result.trim();
}//reverseWords
}//Solution
测试代码:
package leetcode1.ReverseWordsinAString;
public class client {
public static void main(String []args){
Solution sol = new Solution();
String str = sol.reverseWords("the sky is blue");
System.out.print(str);
}
}
总结:for(String str:sArray)结构:
是
for
each循环 jdk5中新的遍历方式 就是遍历String类型的list,每个变量为str
通过这个转换String strArray[] = (String [])list.toArray();
思路上:利用字符串的split()方法以空格符为分解符,截取出每一段并放入到数组中,利用数组循环添加
其他思路:总体先倒转一下,每个单词再倒转一下