classSolution { publicintcountHomogenous(String s) { intn= s.length(), MOD = (int)1e9+7; longans=0; for (inti=0; i < n; ) { intj= i; while (j < n && s.charAt(j) == s.charAt(i)) j++; longcnt= j - i; ans += (1 + cnt) * cnt / 2; ans %= MOD; i = j; } return (int) ans; } }
C++ 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intcountHomogenous(string s){ int n = s.size(), MOD = 1e9+7; long ans = 0; for (int i = 0; i < n; ) { int j = i; while (j < n && s[j] == s[i]) j++; long cnt = j - i; ans += (1 + cnt) * cnt / 2; ans %= MOD; i = j; } return (int) ans; } };
Python3 代码:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defcountHomogenous(self, s: str) -> int: n, mod, i, ans = len(s), 1e9+7, 0, 0 while i < n: j = i while j < n and s[j] == s[i]: j += 1 cnt = j - i ans += (cnt + 1) * cnt / 2 ans %= mod i = j returnint(ans)
TypeScript 代码:
1 2 3 4 5 6 7 8 9 10 11 12
functioncountHomogenous(s: string): number { let n = s.length, mod = 1e9+7, ans = 0 for (let i = 0; i < n; ) { let j = i while (j < n && s.charAt(j) == s.charAt(i)) j++ const cnt = j - i ans += (1 + cnt) * cnt / 2 ans %= mod i = j } return ans }