2000. 反转单词前缀题解
题目来源:2000. 反转单词前缀
2022.2.1每日一题
解题思路:在字符串之中找到所要求的字符 ch ,如果找到了,则对其以及之前的字符串进行翻转,反之则没有任何的操作
法一:直接转换
具体代码以及注释如下
C++代码
class Solution {
public:
string reversePrefix(string word, char ch) {
// 查找字符 ch 第一次出现的位置,若没有找到则返回 -1
int index = word.find(ch);
// 当 ch 第一次出现时的位置是第一位时,也相当于不需要操作
if (index < 1) {
return word;
}
// 翻转字符串
reverse(word.begin(), word.begin() + index + 1);
return word;
}
};
// 时间复杂度为O(n),空间复杂度为O(1)
Java代码
class Solution {
public static String reversePrefix(String word, char ch) {
// 查找字符 ch 第一次出现的位置,若没有找到则返回 -1
int index = word.indexOf(ch);
// 当 ch 第一次出现时的位置是第一位时,也相当于不需要操作
if (index < 1) {
return word;
}
// 翻转字符串
// 截取字符串,前一部分需要进行翻转操作
String change = word.substring(0, index + 1);
// 后一部分无需操作
String left = word.substring(index + 1);
// 将反转完成和原本剩余的两个字符串进行拼接
return new StringBuffer(change).reverse().toString() + left;
}
}
// 时间复杂度为O(n),空间复杂度为O(n)
法二:双指针
具体代码以及注释如下
C++代码
class Solution {
public:
string reversePrefix(string word, char ch) {
// 查找字符 ch 第一次出现的位置,若没有找到则返回 -1
int flag = word.find(ch);
// 当 ch 第一次出现时的位置是第一位时,也相当于不需要操作
if (flag < 1) {
return word;
}
// 返回结果
return change(word, flag);
}
string change(string &s, int f) {
// 对相应字符进行对调
int l = 0, r = f;
while (l <= r) {
swap(s[l], s[r]);
l++;
r--;
}
// 返回翻转以后结果
return s;
}
};
// 时间复杂度为O(n),空间复杂度为O(1)
Java代码
public static String reversePrefix(String word, char ch) {
// 查找字符 ch 第一次出现的位置,若没有找到则返回 -1
int index = word.indexOf(ch);
// 当 ch 第一次出现时的位置是第一位时,也相当于不需要操作
if (index < 1) {
return word;
}
int l = 0, r = index;
StringBuffer sb = new StringBuffer(word);
while (l <= r) {
// 对相应字符进行对调
char temp = word.charAt(l);
sb.setCharAt(l, word.charAt(r));
sb.setCharAt(r, temp);
l++;
r--;
}
// 返回结果
return sb.toString();
}
// 时间复杂度为O(n),空间复杂度为O(n)