File tree 1 file changed +17
-25
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +17
-25
lines changed Original file line number Diff line number Diff line change 2
2
3
3
public class _1576 {
4
4
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
+ */
5
8
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
+ }
14
22
}
15
23
}
16
- return sb . toString ( );
24
+ return String . valueOf ( arr );
17
25
}
18
26
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
- }
35
27
}
36
28
}
You can’t perform that action at this time.
0 commit comments