Java provides some apis make this question tricky. Like String.reverse(), or even String.split(" ") also eases this problem. The code below has few places confusing, as the leetcode compiling rules are.
The solution below uses String loop instead of String.split("") as commented in the code. The basic idea is to reverse the entire String first then reverse the words in the String which are splitter by space.
The reverse function has multiple ways too even though basic ideas are the same. Like I defined a StringBuilder since any operations on String will cause reductant objects initialized. Anyway swap inside the String will work too, and looked smarter.
public class Solution {
public String reverseWords(String s) {
if(s == null || s.length() == 0){
return s;
}
// String[] words = s.split(" ");
// StringBuilder result = new StringBuilder();
// for(int i = words.length - 1; i >= 0; i--){
// if(!words[i].equals(" ") && !words[i].equals("")){
// result.append((words[i]) + " ");
// }
// }
// if(result.length() == 0)
// return result.toString();
// return result.substring(0, result.length() - 1);
String preProcess = reverseOperation(s);
// String[] words = preProcess.split(" ");
// if(words.length == 0){
// return "";
// }
StringBuilder result = new StringBuilder();
// for(String word : words){
// if(!word.equals(""))
// result.append(reverseOperation(word) + " ");
// }
// if(end > begin){
// result.append(reverseOperation(preProcess.substring(begin, end)));
// }
int begin = 0;
int end = begin;
preProcess = preProcess + " ";
for(int i = 0; i < preProcess.length(); i++){
if(preProcess.charAt(i) == ' '){
if(end > begin){
String cur = preProcess.substring(begin, end);
result.append(reverseOperation(cur));
result.append(" ");
}
begin = i;
end = begin;
}else{
if(begin == end){
begin = i;
end = begin + 1;
}else{
end++;
}
}
}
return result.toString().trim();
}
private String reverseOperation(String input){
StringBuilder buffer = new StringBuilder();
int length = input.length() - 1;
for(int i = length; i >= 0; i--){
buffer.append(input.charAt(i));
}
return buffer.toString();
}
}
没有评论:
发表评论