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"
Note:
1 <= s.length <= 4 * 10^5
s contains only lowercase English letters.
解法:先找到lexicographical最大的字符,然后确定他们所在的index,然后每次都比较所有index后面的一个字符,保持最大的那些,其他的都删掉。然后删至只有一个,返回这个对应的最开始的index,返回s.substring(index)即可。
class Solution {
public String lastSubstring(String s) {
if (s == null || s.length() <= 1) return s;
char max = 'a';
char sam = s.charAt(0);
boolean same = true;
for (int i = 1; i < s.length(); i++) if (s.charAt(i) != sam) same = false;
if (same) return s;
for (int i = 0; i < s.length(); i++) if (s.charAt(i) > max) max = s.charAt(i);
List<node> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) if (s.charAt(i) == max) list.add(new node(i, i));
if (list.size() == 1) return s.substring(list.get(0).original);
while (true) {
char x = 'a';
for (node n : list) {
n.index += 1;
if (n.index < s.length() && s.charAt(n.index) > x) x = s.charAt(n.index);
}
List<node> newList = new ArrayList<>();
for (node n : list) {
if (n.index < s.length() && s.charAt(n.index) == x) newList.add(n);
}
if (newList.size() == 1) return s.substring(newList.get(0).original);
list = newList;
}
}
public class node {
int index;
int original;
public node(int index, int original) {
this.index = index;
this.original = original;
}
}
}