题目描述
题目一:翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。
例如输入字符串“I am a student.”,则输出“student. a am I”
练习地址
lc-有点不同-需要去掉多余空格->jz可多写一个方法
实现
方法:
先翻转整个句子,然后,依次翻转每个单词。
依据空格来确定单词的起始和终止位置
public class C58_string_Reverse {
public static String reverseSentence(String str) {
char[] chars = str.toCharArray();
// 翻转句子里所有的char字符
reverse(chars, 0, chars.length - 1);
int blank = -1;// 单词开始的index
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' '){// 无法遍历到最后一个单词
int nextBlank = i;// 空格的index,单词结束的下一个index
reverse(chars, blank + 1, nextBlank - 1);
blank = nextBlank;
}
}
//最后一个单词单独进行反转
reverse(chars, blank + 1, chars.length - 1);
return new String(chars);
}
// 翻转每个单词
public static void reverse(char[] chars, int low, int high) {
while (low < high) {
// 前后对应位置对调
char temp = chars[low];
chars[low] = chars[high];
chars[high] = temp;
low++;
high--;
}
}
}
实现-lc
有点不同:需要去掉多余空格 lc_method
时间复杂度 O(N)O: 总体为线性时间复杂度,各函数时间复杂度和参考资料链接如下。
split() 方法: 为 O(N) ;
trim() 和 strip() 方法: 最差情况下(当字符串全为空格时),为 O(N);
join() 方法: 为 O(N) ;
reverse() 方法: 为 O(N);
空间复杂度 O(N) : 单词列表 strsstrs 占用线性大小的额外空间。
class Solution {
public String reverseWords(String s) {
String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串
StringBuilder res = new StringBuilder();
for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
if(strs[i].equals("")) continue; // 遇到空单词则跳过
res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
}
return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
}
}
Test
public static void main(String[] args) {
String str="I am a student.";
System.out.println(str);
System.out.println(reverseSentence(str));
}