Hard
Given a string s
, return the last substring of s
in lexicographical order.
Example 1:
Input: s = “abab”
Output: “bab”
Explanation: The substrings are [“a”, “ab”, “aba”, “abab”, “b”, “ba”, “bab”]. The lexicographically maximum substring is “bab”.
Example 2:
Input: s = “leetcode”
Output: “tcode”
Constraints:
1 <= s.length <= 4 * 105
s
contains only lowercase English letters.class Solution {
fun lastSubstring(s: String): String {
var i = 0
var j = 1
var k = 0
val n = s.length
val ca = s.toCharArray()
while (j + k < n) {
if (ca[i + k] == ca[j + k]) {
k++
} else if (ca[i + k] > ca[j + k]) {
j += k + 1
k = 0
} else {
i = Math.max(i + k + 1, j)
j = i + 1
k = 0
}
}
return s.substring(i)
}
}