【字符串】A052_LC_按字典序排在最后的子串(最大后缀)

一、Problem

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

Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. 
The lexicographically maximum substring is "bab".

Note:

1 <= s.length <= 4 * 10^5
s contains only lowercase English letters.

二、Solution

方法一:最大后缀

Q:为什么答案一定是字符串 s 的最大后缀?

反证法证明:假设这个字典序最大的子串是 ans,并且 ans 不是后缀,那么 ans 连接上它后面的若干字符构成的新字符串的字典序一定比 ans 大,这和 s 是字典序最大的子串相矛盾,所以只有当 ans 是后缀且字典序最大的情况下,ans 是答案才能成立。

class Solution {
    public String lastSubstring(String s) {
        Set<Character> st = new TreeSet<>();
        for (char c : s.toCharArray()) 
            st.add(c);
        if (st.size() == 1)
            return s;
        
        StringBuilder sb = new StringBuilder();
        Object[] cs = st.toArray();

        for (int i = st.size()-1; i >= 0; i--) {
            sb.append(cs[i]);
            while (true) {
                if (s.contains(sb.toString()))
                    sb.append(cs[i]);
                else {
                    sb.deleteCharAt(sb.length()-1);
                    break;
                }
            }
        }
        return s.substring(s.indexOf(sb.toString()));
    }
}

复杂度分析

  • 时间复杂度: O ( . . . ) O(...)
  • 空间复杂度: O ( . . . ) O(...)

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/106874699