classSolution { public: boolcheckDistances(string s, vector<int>& distance){ vector<int> firstIndex(26); for (int i = 0; i < s.size(); i++) { int idx = s[i] - 'a'; if (firstIndex[idx] && i - firstIndex[idx] != distance[idx]) { returnfalse; } firstIndex[idx] = i + 1; } returntrue; } };
[sol2-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicbooleancheckDistances(String s, int[] distance) { int[] firstIndex = newint[26]; for (inti=0; i < s.length(); i++) { intidx= s.charAt(i) - 'a'; if (firstIndex[idx] != 0 && i - firstIndex[idx] != distance[idx]) { returnfalse; } firstIndex[idx] = i + 1; } returntrue; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defcheckDistances(self, s: str, distance: List[int]) -> bool: n = len(s) firstIndex = [0] * 26; for i inrange(n): idx = ord(s[i]) - ord('a'); if firstIndex[idx] and i - firstIndex[idx] != distance[idx]: returnFalse firstIndex[idx] = i + 1 returnTrue
[sol2-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { publicboolCheckDistances(string s, int[] distance) { int[] firstIndex = newint[26]; for (int i = 0; i < s.Length; i++) { int idx = s[i] - 'a'; if (firstIndex[idx] != 0 && i - firstIndex[idx] != distance[idx]) { returnfalse; } firstIndex[idx] = i + 1; } returntrue; } }
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11 12 13
boolcheckDistances(char * s, int* distance, int distanceSize) { int n = strlen(s); int firstIndex[26]; memset(firstIndex, 0, sizeof(firstIndex)); for (int i = 0; i < n; i++) { int idx = s[i] - 'a'; if (firstIndex[idx] && i - firstIndex[idx] != distance[idx]) { returnfalse; } firstIndex[idx] = i + 1; } returntrue; }
[sol2-Go]
1 2 3 4 5 6 7 8 9 10 11
funccheckDistances(s string, distance []int)bool { firstIndex := make([]int, 26) for i := 0; i < len(s); i++ { idx := s[i] - 'a' if firstIndex[idx] != 0 && i - firstIndex[idx] != distance[idx] { returnfalse } firstIndex[idx] = i + 1 } returntrue }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11
var checkDistances = function(s, distance) { let firstIndex = newArray(26).fill(0); for (let i = 0; i < s.length; i++) { let idx = s.charCodeAt(i) - 'a'.charCodeAt(0); if (firstIndex[idx] != 0 && i - firstIndex[idx] != distance[idx]) { returnfalse; } firstIndex[idx] = i + 1; } returntrue; };
复杂度分析
时间复杂度:O(n),其中 n 表示字符串的长度。只需要遍历字符串一次即可,总的时间复杂度为 O(n)。