classSolution { public: string lastSubstring(string s){ int i = 0, j = 1, n = s.size(); while (j < n) { int k = 0; while (j + k < n && s[i + k] == s[j + k]) { k++; } if (j + k < n && s[i + k] < s[j + k]) { int t = i; i = j; j = max(j + 1, t + k + 1); } else { j = j + k + 1; } } return s.substr(i, n - i); } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public String lastSubstring(String s) { inti=0, j = 1, n = s.length(); while (j < n) { intk=0; while (j + k < n && s.charAt(i + k) == s.charAt(j + k)) { k++; } if (j + k < n && s.charAt(i + k) < s.charAt(j + k)) { intt= i; i = j; j = Math.max(j + 1, t + k + 1); } else { j = j + k + 1; } } return s.substring(i); } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: deflastSubstring(self, s: str) -> str: i, j, n = 0, 1, len(s) while j < n: k = 0 while j + k < n and s[i + k] == s[j + k]: k += 1 if j + k < n and s[i + k] < s[j + k]: i, j = j, max(j + 1, i + k + 1) else: j = j + k + 1 return s[i:]
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var lastSubstring = function(s) { let i = 0, j = 1, n = s.length; while (j < n) { let k = 0; while (j + k < n && s[i + k] === s[j + k]) { k++; } if (j + k < n && s[i + k] < s[j + k]) { let t = i; i = j; j = Math.max(j + 1, t + k + 1); } else { j = j + k + 1; } } return s.substring(i, n); };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicstringLastSubstring(string s) { int i = 0, j = 1, n = s.Length; while (j < n) { int k = 0; while (j + k < n && s[i + k] == s[j + k]) { k++; } if (j + k < n && s[i + k] < s[j + k]) { int t = i; i = j; j = Math.Max(j + 1, t + k + 1); } else { j = j + k + 1; } } return s.Substring(i); } }
char * lastSubstring(char * s) { int i = 0, j = 1, n = strlen(s); while (j < n) { int k = 0; while (j + k < n && s[i + k] == s[j + k]) { k++; } if (j + k < n && s[i + k] < s[j + k]) { int t = i; i = j; j = MAX(j + 1, t + k + 1); } else { j = j + k + 1; } } char *res = (char *)calloc(n - i + 1, sizeof(char)); strncpy(res, s + i, n - i); return res; }
复杂度分析
时间复杂度:O(n),其中 n 是字符串 s 的长度。每 k 次比较,i 与 j 共同至少向右移动 k,因此总比较次数不超过 2 \times n 次。