Given a string s
, return the last substring of s
in lexicographical order.
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: "leetcode"
Output: "tcode"
思路:用i, j来表示最佳答案的起点,首先明确,substring都是从i到最后的substring。如果ss[i + k] ss[j + k]相等,k++,如果ss[i + k] < ss[j + k] 那么更新i = j, j = i + 1,继续找,如果ss[i + k] > ss[j + k]说明当前i仍然是最佳答案,j ++; Time: O(n) ,Space: O(1);
We use "j" to find a better starting index. If any is found, we use it to update "i"
1."i" is the starting index of the first substring
2."j" is the staring index of the second substring
3."k" is related to substring.length() (eg. "k" is substring.length()-1)
Case 1 (s[i+k]==s[j+k]):
-> If s.substr(i,k+1)==s.substr(j,k+1), we keep increasing k.
Case 2 (s[i+k]<s[j+k]):
-> If the second substring is larger, we update i with j. (The final answer is s.substr(i))
Case 3 (s[i+k]>s[j+k]):
-> If the second substring is smaller, we just change the starting index of the second string to j+k+1. Because s[j]~s[j+k] must be less than s[i], otherwise "i" will be updated by "j". So the next possible candidate is "j+k+1".
class Solution {
public String lastSubstring(String s) {
if(s == null || s.length() == 0) {
return s;
}
int i = 0;
int j = 1; // 找另外一个解;
int k = 0;
while(j + k < s.length()) {
if(s.charAt(i + k) == s.charAt(j + k)) {
k++;
continue;
}
if(s.charAt(i + k) < s.charAt(j + k)) {
i = j;
j = i + 1;
k = 0;
} else {
// ss[i + k] > ss[j + k];
j++;
k = 0;
}
}
return s.substring(i);
}
}