题目
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note:In the string, each word is separated by single space and there will not be any extra space in the string.
题意
对句子中每个单词进行字符串反转。
分析及解答
解答1:(效率更高)
- 通过 start , end 记录 处理的句子的状态。start 和 end表示了一个单词。
- 重复计算更少(相对于解法2).
public class Solution {
public String reverseWords(String s) {
char[] charArray = s.toCharArray();
int end = 0;
int start = 0;
while((end = find(charArray,start,' ')) != -1){
//Reverse each word in the string
reverse(charArray,start,end-1);
start = end+1;
}
//Reverse the last word
reverse(charArray,start,s.length()-1);
return new String(charArray);
}
public static int find(char[] a, int start, char c){
for(int i=start;i<a.length;i++){
if(a[i] == c){
return i;
}
}
return -1;
}
public static void reverse(char[] strArray,int start, int end){
while(start<end){
char temp = strArray[start];
strArray[start] = strArray[end];
strArray[end] = temp;
start++;
end--;
}
}
}
解法2:(我的做法)
- 未使用双指针。
public class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder results = new StringBuilder();
for(String word : words){
char[] restult = word.toCharArray();
for(int i = 0 ; i <restult.length/2 ; i++ ){
char tmp = restult[i];
restult[i] = restult[restult.length - 1 - i];
restult[restult.length - 1 - i] = tmp;
}
results.append(String.valueOf(restult)).append(" ");
}
if(results.lastIndexOf(" ") == -1){
return results.toString();
}else{
return results.substring(0, results.lastIndexOf(" ")).toString();
}
}
}