Algorithm
Problem Name: 1163. Last Substring in Lexicographical Order
Given a string s
, return the last substring of s
in lexicographical order.
Example 1:
Input: s = "abab" Output: "bab" Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
Example 2:
Input: s = "leetcode" Output: "tcode"
Constraints:
1 <= s.length <= 4 * 105
s
contains only lowercase English letters.
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const lastSubstring = function(s) {
let ans = '',
max = 'a'
for (let i = 0; i < s.length; ) {
let j = i,
sub = s.slice(i)
if (max < s[i] || ans < sub) {
max = s[i]
ans = sub
}
while (i < s.length && s[i + 1] === s[i]) {
i++
}
if (j === i) {
i++
}
}
return ans
}
Copy The Code &
Try With Live Editor
Input
s = "abab"
Output
"bab"
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def lastSubstring(self, s: str) -> str:
result = ""
for i in range(len(s)):
result = max(result, s[i:])
return result
Copy The Code &
Try With Live Editor
Input
s = "abab"
Output
"bab"