给定字符串s,按字典顺序返回s的最后一个子字符串。
样例
例 1:
输入: “abab”
输出: “bab”
解释: s的子串为 [“a”, “ab”, “aba”, “abab”, “b”, “ba”, “bab”].
其中字典序最后的子串为 “bab”.
例 2:
输入: “baca”
输出: “ca”
注意事项
1 <= s.length <= 4 * 10^4
s仅包含小写英文字母。
class Solution {
public:
/**
* @param s: the matrix
* @return: the last substring of s in lexicographical order
*/
/*
算法:
结果肯定是最大字母到结尾的字串//这个是重点
找出所有最大字母到结尾的子串
排序,取最后一个
*/
vector<int>max_index; //保存每一个最大元素的下标
void findMaxIndex(string s, string max) //将s中的所有max元素的下标保存在max_index
{
if (s == "")
return;
string::size_type pos = s.find(max);
if (pos == string::npos)
return;
else
{
max_index.push_back(pos);
}
string newSub = s.replace(s.begin() + pos, s.begin() + pos + 1, "a");
findMaxIndex(newSub, max);
}
string maxSubstring(string &s) {
// Write your code here.
if (s == "")
return NULL;
string lastStr;
string::iterator it = max_element(s.begin(), s.end());
string max;
max=*it;
findMaxIndex(s, max);
vector<string>res;//保存以最大字母为首,到结尾的子串
for (int i = 0; i < max_index.size(); i++)
{
int pos = max_index[i];
string tmp = s.substr(pos,s.length()-pos );
res.push_back(tmp);
}
sort(res.begin(), res.end());
lastStr = res[res.size()-1];
return lastStr;
}
};