给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入: “Let’s take LeetCode contest”
输出: “s’teL ekat edoCteeL tsetnoc”
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
思路:
题解1: 利用栈来翻转string, 效率很低很慢.
题解2: 移除了栈, 效率高了三倍
题解3: 移除了StringBuffer, 慢出天际…
题解1:
class Solution {
public String reverseWords(String s) {
StringBuffer result=new StringBuffer();
Stack stack=new Stack();
char[] wordArr=s.toCharArray();
for(int i=0; i<wordArr.length; i++){
char c=wordArr[i];
if(c!=' ')
stack.push(c);
if(c==' '||i==wordArr.length-1){
while(stack.size()>0){
result.append(stack.pop());
}
if(c==' ')
result.append(c);
}
}
return result.toString();
}
}
题解2:
class Solution {
public String reverseWords(String s) {
StringBuffer buffer=new StringBuffer();
for(String word: s.split(" ")){
StringBuffer newWord=new StringBuffer();
char[] wordArr=word.toCharArray();
for(int i=word.length()-1; i>=0; i--){
newWord.append(wordArr[i]);
}
buffer.append(newWord);
buffer.append(" ");
}
String result=buffer.toString();
result=result.substring(0, result.length()-1);
return result;
}
}
题解3:
class Solution {
public String reverseWords(String s) {
String result="";
for(String word: s.split(" ")){
String newWord="";
char[] wordArr=word.toCharArray();
for(int i=word.length()-1; i>=0; i--){
newWord+=wordArr[i];
}
result+=newWord;
result+=" ";
}
result=result.substring(0, result.length()-1);
return result;
}
}