LeetCode 1163. Last Substring in Lexicographical Order(java)

本文介绍了一种算法,用于从给定字符串中找出字典序最大的子串。通过定位最大字符,筛选并比较其后的字符,最终确定目标子串。适用于长度可达40万的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值