我可以帮助您翻译。下面的代码被编写用于替换字符串中的每个问号,以便不会出现相同的字母相邻。例如:
输入
请注意,
输入
ab?ac?
输出
abcaca
请注意,
?
应替换为任何小写字母:[a-z]
以下是我的解决方案。但我的问题是:是否有更优化的方法来解决这个问题?public String solution(String riddle) {
char alpha[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
if (riddle == null || riddle.indexOf('?') == -1) {
return riddle;
}
StringBuilder sb = new StringBuilder("");
int cnt = 0;
for (int i = 0; i < riddle.length(); i++) {
char current = riddle.charAt(i);
char prev = '\0';
char next = '\0';
if (current == '?') {
current = alpha[cnt];
if (i != 0) {
prev = sb.toString().charAt(i - 1);
}
if (i != riddle.length() - 1) {
next = riddle.charAt(i + 1);
}
while (current == prev || current == next) {
current = alpha[++cnt];
if (cnt % 25 == 0) {
cnt = 0;
}
}
sb.append(current);
} else {
sb.append(current);
}
}
return sb.toString();
}
O(n)
了,我认为不可能比这更好了。 - Lrrr