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.

思路:找到最后一个字母最大的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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值