[LeetCode] Last Substring in Lexicographical Order

1163. Last Substring in Lexicographical Order

Given a string s, return the last substring of s in lexicographical order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string lastSubstring(string s) {
int n = s.length(), res = n - 1, i = n - 1;

while(i >= 0) {
if(s[i] > s[res]) {
res = i;
} else if(s[i] == s[res]) {
int j = 1;

while(res + j < n and s[res + j] == s[i + j] and i + j != res) j++;
if(res + j >= n or s[res + j] <= s[i + j])
res = i;

}
i--;
}

return s.substr(res);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/02/PS/LeetCode/last-substring-in-lexicographical-order/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.