LeetCode //C - 1163. Last Substring in Lexicographical Order

发布时间:2026/7/26 22:51:47
LeetCode //C - 1163. Last Substring in Lexicographical Order 1163. Last Substring in Lexicographical OrderGiven a string s, returnthe 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 . l e n g t h 4 ∗ 10 5 1 s.length 4 * 10^51s.length4∗105s contains only lowercase English letters.From: LeetCodeLink: 1163. Last Substring in Lexicographical OrderSolution:Ideas:Maintain two candidate starting positions i and j, compare their suffixes character by character, and discard the lexicographically smaller candidate each time so every position is processed at most once in O(n) time.Code:char*lastSubstring(char*s){intnstrlen(s);inti0,j1,k0;while(jn){k0;while(jkns[ik]s[jk]){k;}if(jkn){break;}if(s[ik]s[jk]){iik1;if(ij){ji1;}}else{jjk1;}}returnsi;}