File tree Expand file tree Collapse file tree 1 file changed +17
-25
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +17
-25
lines changed Original file line number Diff line number Diff line change 22
33public 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}
You can’t perform that action at this time.
0 commit comments