classSolution: defsumScores(self, s: str) -> int: n = len(s) z = [0] * n ans, l, r = n, 0, 0 for i inrange(1, n): z[i] = max(min(z[i - l], r - i + 1), 0) # 注:不用 min max,拆开用 < > 比较会更快(仅限于 Python) while i + z[i] < n and s[z[i]] == s[i + z[i]]: l, r = i, i + z[i] z[i] += 1 ans += z[i] return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publiclongsumScores(String s) { varn= s.length(); varz=newint[n]; longans= n; for (inti=1, l = 0, r = 0; i < n; i++) { z[i] = Math.max(Math.min(z[i - l], r - i + 1), 0); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) { l = i; r = i + z[i]; z[i]++; } ans += z[i]; } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: longlongsumScores(string s){ int n = s.length(); long ans = n; vector<int> z(n); for (int i = 1, l = 0, r = 0; i < n; ++i) { z[i] = max(min(z[i - l], r - i + 1), 0); while (i + z[i] < n && s[z[i]] == s[i + z[i]]) { l = i; r = i + z[i]; ++z[i]; } ans += z[i]; } return ans; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funcsumScores(s string)int64 { n := len(s) z := make([]int, n) ans := n for i, l, r := 1, 0, 0; i < n; i++ { z[i] = max(min(z[i-l], r-i+1), 0) for i+z[i] < n && s[z[i]] == s[i+z[i]] { l, r = i, i+z[i] z[i]++ } ans += z[i] } returnint64(ans) }
funcmin(a, b int)int { if a > b { return b }; return a } funcmax(a, b int)int { if a < b { return b }; return a }