Given a string s, return the last substring of s in lexicographical order.
Example
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: "baca"
Output: "ca"
Notice
1 <= s.length <= 4 * 10^4
s contains only lowercase English letters.
思路:找到最后一个字母最大的char,然后以这个字母到最尾巴的substring就是所有的可能的最大substring,然后写个比较器,排在最后的那个就是答案。
public class Solution {
/**
* @param s: the matrix
* @return: the last substring of s in lexicographical order
*/
public String maxSubstring(String s) {
if(s == null || s.length() == 0) return s;
int[] charIndex = new int[26];
for(int i= 0; i<charIndex.length; i++){
charIndex[i] = -1;
}
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
charIndex[c-'a'] = i;
}
int lastBigCharIndex = charIndex.length-1;
for(int i=charIndex.length-1; i>=0; i--){
if(charIndex[i] != -1) {
lastBigCharIndex = charIndex[i];
break;
}
}
// find all substring, beginwith lastBigChar;
String lastResult = null;
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == s.charAt(lastBigCharIndex)){
String substr = s.substring(i);
if(lastResult == null) {
lastResult = substr;
} else {
if(lessthan(lastResult, substr)) {
lastResult = substr;
}
}
}
}
return lastResult;
}
private boolean lessthan(String a, String b) {
int i = 0; int j = 0;
while(i < a.length() && j < b.length()){
char ac = a.charAt(i);
char bc = b.charAt(j);
if(ac < bc) {
return true;
} else if(ac > bc) {
return false;
} else {
// ac == bc;
i++;
j++;
}
}
if(i == a.length() && j < b.length()){
return true;
}
if(j == b.length() && i < a.length()){
return false;
}
return false;
}
}