这个题目很简单,记录别人的做法,供自己学习
分别是:几乎全调用函数&函数自己实现
1.全部调用函数:
public class Solution {
public String reverseWords(String s) {
String words[] = s.split(" ");
StringBuilder res=new StringBuilder();
for (String word: words)
res.append(new StringBuffer(word).reverse().toString() + " ");
return res.toString().trim();
}
}
其中:
split函数为按照正则表达式分割字符串
for(String word:words)遍历串
append函数,注意StringBuilder提供,String不支持
reverse()函数,反转
StringBuilder.toString(),类型转换,常用for me
trim()函数,删掉首尾的空白,常用for me
2.上述函数自定义:
public class Solution {
public String reverseWords(String s) {
String words[] = split(s);
StringBuilder res=new StringBuilder();
for (String word: words)
res.append(reverse(word) + " ");
return res.toString().trim();
}
public String[] split(String s) {
ArrayList < String > words = new ArrayList < > ();
StringBuilder word = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
words.add(word.toString());
word = new StringBuilder();
} else
word.append( s.charAt(i));
}
words.add(word.toString());
return words.toArray(new String[words.size()]);
}
public String reverse(String s) {
StringBuilder res=new StringBuilder();
for (int i = 0; i < s.length(); i++)
res.insert(0,s.charAt(i));
return res.toString();
}
}
从单个字符的角度来处理字符串
对一行字符串的每一个字符都有处理
先把句子按照空格拆分成单词
接着把每个单词作为一个数组遍历颠倒
最后将各个单词连接后返回