Last Substring in Lexicographical Order

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"

思路:用i, j来表示最佳答案的起点,首先明确,substring都是从i到最后的substring。如果ss[i + k] ss[j + k]相等,k++,如果ss[i + k] < ss[j + k] 那么更新i = j, j = i + 1,继续找,如果ss[i + k] > ss[j + k]说明当前i仍然是最佳答案,j ++; Time: O(n) ,Space: O(1);

We use "j" to find a better starting index. If any is found, we use it to update "i"

1."i" is the starting index of the first substring
2."j" is the staring index of the second substring
3."k" is related to substring.length() (eg. "k" is substring.length()-1)

Case 1 (s[i+k]==s[j+k]):
-> If s.substr(i,k+1)==s.substr(j,k+1), we keep increasing k.
Case 2 (s[i+k]<s[j+k]):
-> If the second substring is larger, we update i with j. (The final answer is s.substr(i))
Case 3 (s[i+k]>s[j+k]):
-> If the second substring is smaller, we just change the starting index of the second string to j+k+1. Because s[j]~s[j+k] must be less than s[i], otherwise "i" will be updated by "j". So the next possible candidate is "j+k+1".

class Solution {
    public String lastSubstring(String s) {
        if(s == null || s.length() == 0) {
            return s;
        }
        int i = 0;
        int j = 1; // 找另外一个解;
        int k = 0;
        while(j + k < s.length()) {
            if(s.charAt(i + k) == s.charAt(j + k)) {
                k++;
                continue;
            }
            if(s.charAt(i + k) < s.charAt(j + k)) {
                i = j;
                j = i + 1;
                k = 0;
            } else {
                // ss[i + k] > ss[j + k];
                j++;
                k = 0;
            }
        }
        return s.substring(i);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值