classSolution { public String modifyString(String s) { intn= s.length(); char[] arr = s.toCharArray(); for (inti=0; i < n; ++i) { if (arr[i] == '?') { for (charch='a'; ch <= 'c'; ++ch) { if ((i > 0 && arr[i - 1] == ch) || (i < n - 1 && arr[i + 1] == ch)) { continue; } arr[i] = ch; break; } } } returnnewString(arr); } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: string modifyString(string s){ int n = s.size(); for (int i = 0; i < n; ++i) { if (s[i] == '?') { for (char ch = 'a'; ch <= 'c'; ++ch) { if ((i > 0 && s[i - 1] == ch) || (i < n - 1 && s[i + 1] == ch)) { continue; } s[i] = ch; break; } } } return s; } };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassSolution { publicstringModifyString(string s) { int n = s.Length; char[] arr = s.ToCharArray(); for (int i = 0; i < n; ++i) { if (arr[i] == '?') { for (char ch = 'a'; ch <= 'c'; ++ch) { if ((i > 0 && arr[i - 1] == ch) || (i < n - 1 && arr[i + 1] == ch)) { continue; } arr[i] = ch; break; } } } returnnew String(arr); } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char * modifyString(char * s) { int n = strlen(s); for (int i = 0; i < n; ++i) { if (s[i] == '?') { for (char ch = 'a'; ch <= 'c'; ++ch) { if ((i > 0 && s[i - 1] == ch) || (i < n - 1 && s[i + 1] == ch)) { continue; } s[i] = ch; break; } } } return s; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var modifyString = function(s) { const n = s.length; const arr = [...s]; for (let i = 0; i < n; ++i) { if (arr[i] === '?') { for (let j = 0; j < 3; ++j) { if ((i > 0 && arr[i - 1] === String.fromCharCode('a'.charCodeAt() + j)) || (i < n - 1 && arr[i + 1] === String.fromCharCode('a'.charCodeAt() + j))) { continue; } arr[i] = String.fromCharCode('a'.charCodeAt() + j); break; } } } return arr.join(''); };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcmodifyString(s string)string { res := []byte(s) n := len(res) for i, ch := range res { if ch == '?' { for b := byte('a'); b <= 'c'; b++ { if !(i > 0 && res[i-1] == b || i < n-1 && res[i+1] == b) { res[i] = b break } } } } returnstring(res) }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmodifyString(self, s: str) -> str: res = list(s) n = len(res) for i inrange(n): if res[i] == '?': for b in"abc": ifnot (i > 0and res[i - 1] == b or i < n - 1and res[i + 1] == b): res[i] = b break return''.join(res)
复杂度分析
时间复杂度:O(C \times n),其中 n 是字符串的长度,我们需要遍历一遍字符串,C 表示可替代字符的数量,在本题中 C=3。