LintCode 1648: max substring

本文介绍如何解决给定字符串问题,即找出按字典序最后的子串。通过遍历最大字符并寻找其出现位置,找到s中的最长字典序子串。理解并实现一种高效的解法,适用于长度小于40000的英文小写字母字符串。

1648. max substring

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.

Input test data (one parameter per line)How to understand a testcase?

 

解法1:
首先我们要认识到一点,那就是最后的结果一定是以s字符串中某个最大的字符开始到结尾。注意s里面最大的字符可能出现很多次,我们只需遍历这些最大字符出现的地方i,找到s.substr(i)的最大值即可。
举例:
1)s = "cabcba",result = "cba"。
2)s = “cbacab”,result = "cbacab"。
3)s = "cabcbaab", result = "cbaab"。
4)s = "cbacabab",result = "cbacabab“。

class Solution {
public:
    /**
     * @param s: the matrix
     * @return: the last substring of s in lexicographical order
     */
    string maxSubstring(string &s) {
        int len = s.size();
        if (len == 0) return "";
        string result = "";
        char largestChar = 'a';

        for (int i = 0; i < len; ++i) {
            if (largestChar < s[i]) largestChar = s[i];
        }
        
        for (int i = 0; i < len; ++i) {
            if (s[i] == largestChar) {
                result = max(result, s.substr(i));
            }
        }
        
        return result;
    }

};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值