|
2 | 2 |
|
3 | 3 | publicclass_1576 {
|
4 | 4 | publicstaticclassSolution1 {
|
| 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 | publicStringmodifyString(Strings) {
|
6 |
| -StringBuildersb =newStringBuilder(); |
7 |
| -for (inti =0;i <s.length();i++) { |
8 |
| -charc =s.charAt(i); |
9 |
| -if (c =='?') { |
10 |
| -charreplacement =findReplacement(sb,i,s); |
11 |
| -sb.append(replacement); |
12 |
| - }else { |
13 |
| -sb.append(c); |
| 9 | +char[]arr =s.toCharArray(); |
| 10 | +for (inti =0;i <arr.length;i++) { |
| 11 | +if (arr[i] =='?') { |
| 12 | +for (intj =0;j <3;j++) { |
| 13 | +if (i >0 &&arr[i -1] =='a' +j) { |
| 14 | +continue; |
| 15 | + }elseif (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 |
| -returnsb.toString(); |
| 24 | +returnString.valueOf(arr); |
17 | 25 | }
|
18 | 26 |
|
19 |
| -privatecharfindReplacement(StringBuildersb,intindex,Strings) { |
20 |
| -charreplacement ='a'; |
21 |
| -if (index >0) { |
22 |
| -intcount =1; |
23 |
| -while (replacement ==sb.charAt(index -1)) { |
24 |
| -replacement +=count %26; |
25 |
| - } |
26 |
| - } |
27 |
| -if (index +1 <s.length()) { |
28 |
| -intcount =1; |
29 |
| -while (replacement ==s.charAt(index +1) || (index >0 &&replacement ==sb.charAt(index -1))) { |
30 |
| -replacement +=count %26; |
31 |
| - } |
32 |
| - } |
33 |
| -returnreplacement; |
34 |
| - } |
35 | 27 | }
|
36 | 28 | }
|