例如,"student. a am I",正确的句子应该是 "I am a student."
解题思路
先使用空格将字符串切割为字符串数组,再重新拼接新的字符串
public class Solution {
public String ReverseSentence(String str) {
if(str == null || str.trim().length() == 0) {
return str;
}
String[] strs = str.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = strs.length - 1; i >= 0; i--) {
sb.append(strs[i]);
if(i != 0) {
sb.append(" ");
}
}
return sb.toString();
}
}
第二种思路,先翻转整个句子,然后,依次翻转每个单词,依据空格来确定单词的起始和终止位置
public class Solution {
public String ReverseSentence(String str) {
if(str == null || str.trim().length() == 0) {
return str;
}
char[] chars = str.toCharArray();
reverse(chars, 0, chars.length - 1);
int blank = -1;
for(int i = 0; i < chars.length; i++) {
if(chars[i] == ' ') {
int nextBlank = i;
reverse(chars, blank + 1, nextBlank - 1);
blank = nextBlank;
}
}
// 对最后一个单词单独进行反转
reverse(chars, blank + 1, chars.length - 1);
return new String(chars);
}
public void reverse(char[] chars, int low, int high){
while(low < high){
char temp = chars[low];
chars[low] = chars[high];
chars[high] = temp;
low++;
high--;
}
}
}
相关文章
暂无评论...