Last Substring in Lexicographical Order LeetCode solution in C++
1class Solution {2public:3string lastSubstring(string s) {4int maxIndex = s.length() - 1;56for (int currIndex = s.length() - 1; currIndex >= 0; currIndex--) {7if (s[currIndex] > s[maxIndex])8maxIndex = currIndex;910else if (s[currIndex] == s[maxIndex]) {11int i = currIndex + 1;12int j = maxIndex + 1;1314while (i < maxIndex && j < s.length() && s[i] == s[j]) {15i++;16j++;17}1819if (i == maxIndex || j == s.length() || s[i] > s[j]) maxIndex = currIndex;20}21}2223return s.substr(maxIndex);24}25};