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 <= 10^5
- s contains only lowercase English letters.
思路:因为s只有lower case,所以直接考虑按位来考虑
1. 首先开头第一个字母一定是s中最大的char
2. 维护一个index数组表示可能的结果(假设数组内的值为1,5,7,那结果就是从s[1:],s[5:],s[7:]中产生),然后一位一位比较下去,每次比较玩就update这个index数组(有点类似bfs的感觉)
class Solution(object):
def lastSubstring(self, s):
"""
:type s: str
:rtype: str
"""
chars=sorted(list(set([ss for ss in s])))[::-1]
if len(chars)==1: return s
ma=max(s)
q=[]
for i,v in enumerate(s):
if v==ma: q.append(i)
length = 1
while 1:
if len(q)==1: break
qq=[]
for char in chars:
ok=False
for i in q:
if i+length<len(s) and s[i+length]==char:
ok=True
qq.append(i)
if ok: break
length+=1
q,qq=qq,q
idx = q[0]
return s[idx:]