题目.png
题意:给你一个仅包含小写英文字母和 '?' 字符的字符串 s,请你将所有的 '?' 转换为若干小写字母,使最终的字符串不包含任何 连续重复 的字符。
注意:你 不能 修改非 '?' 字符。
题目测试用例保证 除 '?' 字符 之外,不存在连续重复的字符。
在完成所有转换(可能无需转换)后返回最终的字符串。如果有多个解决方案,请返回其中任何一个。可以证明,在给定的约束条件下,答案总是存在的。
解题思路
解法:
1.利用set的不可重复性,存储26个字符
2.开始遍历s字符串数组,每次从set中先把s.charAt(i-1)和s.charAt(i+1)移除,然后更改 s.charAt(i) = set的第一个字符
3.每次遍历完成,记得恢复set,也就是把之前移除的字符,重新添加到里面
4.为了方便更改,直接将s更改为字符串数组cs,方便遍历过程中,直接修改数组元素
解题遇到的问题
其实解题完成之后,思考,不需要26个字符,因为只需要考虑最多三个字符,所以只需要在'a'、'b'、'c'中遍历即可
后续需要总结学习的知识点
无
##解法1
import java.util.HashSet;
class Solution {
public String modifyString(String s) {
char[] cs = s.toCharArray();
// 利用set的不可重复性,存储26个字符
HashSet<Character> set = new HashSet<Character>();
for (int i = 0; i < 26; i++) {
set.add((char) ('a' + i));
}
// 开始遍历s字符串数组,每次从set中先把s.charAt(i-1)和s.charAt(i+1)移除,然后更改 s.charAt(i) =
// set的第一个字符
// 每次遍历完成,记得恢复set,也就是把之前移除的字符,重新添加到里面
// 为了方便更改,直接将s更改为字符串数组cs,方便遍历过程中,直接修改数组元素
if (cs[0] == '?') {
if (cs.length == 1) {
return "a";
}
set.remove(cs[1]);
cs[0] = (char) set.toArray()[0];
set.add(cs[1]);
}
for (int i = 1; i < cs.length - 1; i++) {
char pre = cs[i - 1];
char next = cs[i + 1];
if (cs[i] == '?') {
set.remove(pre);
set.remove(next);
cs[i] = (char) set.toArray()[0];
set.add(pre);
set.add(next);
}
}
if (cs[cs.length - 1] == '?') {
set.remove(cs[cs.length - 2]);
cs[cs.length - 1] = (char) set.toArray()[0];
set.add(cs[cs.length - 2]);
}
return String.valueOf(cs);
}
}