Skip to content

Commit c332206

Browse files
refactor 1576
1 parent 06b5ac6 commit c332206

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed

src/main/java/com/fishercoder/solutions/_1576.java

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,27 @@
22

33
public class _1576 {
44
public static class Solution1 {
5+
/**
6+
* Each char could have at most two neighbors, so we only need to toggle between three character candidates to avoid repetition.
7+
*/
58
public String modifyString(String s) {
6-
StringBuilder sb = new StringBuilder();
7-
for (int i = 0; i < s.length(); i++) {
8-
char c = s.charAt(i);
9-
if (c == '?') {
10-
char replacement = findReplacement(sb, i, s);
11-
sb.append(replacement);
12-
} else {
13-
sb.append(c);
9+
char[] arr = s.toCharArray();
10+
for (int i = 0; i < arr.length; i++) {
11+
if (arr[i] == '?') {
12+
for (int j = 0; j < 3; j++) {
13+
if (i > 0 && arr[i - 1] == 'a' + j) {
14+
continue;
15+
} else if (i < arr.length - 1 && arr[i + 1] == 'a' + j) {
16+
continue;
17+
} else {
18+
arr[i] = (char) ('a' + j);
19+
break;
20+
}
21+
}
1422
}
1523
}
16-
return sb.toString();
24+
return String.valueOf(arr);
1725
}
1826

19-
private char findReplacement(StringBuilder sb, int index, String s) {
20-
char replacement = 'a';
21-
if (index > 0) {
22-
int count = 1;
23-
while (replacement == sb.charAt(index - 1)) {
24-
replacement += count % 26;
25-
}
26-
}
27-
if (index + 1 < s.length()) {
28-
int count = 1;
29-
while (replacement == s.charAt(index + 1) || (index > 0 && replacement == sb.charAt(index - 1))) {
30-
replacement += count % 26;
31-
}
32-
}
33-
return replacement;
34-
}
3527
}
3628
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy