Skip to content

1576. Replace All ?'s to Avoid Consecutive Repeating Characters

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  string modifyString(string s) {
    string ans;

    for (int i = 0; i < s.length(); ++i)
      if (s[i] == '?')
        ans += nextAvailable(ans, s, i);
      else
        ans += s[i];

    return ans;
  }

 private:
  char nextAvailable(const string& ans, const string& s, int i) {
    char c = 'a';
    while ((i > 0 && ans[i - 1] == c) ||  //
           (i + 1 < s.size() && c == s[i + 1]))
      ++c;
    return c;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public String modifyString(String s) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); ++i)
      if (s.charAt(i) == '?')
        sb.append(nextAvailable(sb, s, i));
      else
        sb.append(s.charAt(i));

    return sb.toString();
  }

  private char nextAvailable(StringBuilder sb, final String s, int i) {
    char c = 'a';
    while ((i > 0 && sb.charAt(i - 1) == c) || (i + 1 < s.length() && c == s.charAt(i + 1)))
      ++c;
    return c;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def modifyString(self, s: str) -> str:
    ans = []

    def nextAvailable(ans: list[int], s: str, i: int) -> str:
      c = 'a'
      while ((i > 0 and ans[i - 1] == c) or
             (i + 1 < len(s) and c == s[i + 1])):
        c = chr(ord(c) + 1)
      return c

    for i, c in enumerate(s):
      if c == '?':
        ans.append(nextAvailable(ans, s, i))
      else:
        ans.append(c)

    return ''.join(ans)