**
1.先用dp算出所有的下降子序列
2.将所有最长的下降子序列放入vector中排序
3.先按照所有下降子序列的第一个字符排序,然后舍弃后面的子序列
4.再按照第二个字符排序,再舍弃后面的子序列,直到vector中只剩下一个子序列
**
class Solution {
private:
string text;
int dp[400005];
inline char GetText(int index) {
if (index < text.length()) {
return text[index];
}
return 0;
}
int DfsDp(int index) {
if (-1 != dp[index]) {
return dp[index];
}
dp[index] = 1;
if (text[index] < text[index + 1]) {
DfsDp(index + 1);
}
else {
dp[index] += DfsDp(index + 1);
}
return dp[index];
}
void PrintVector(vector<int> results){
printf("size = %d\n", results.size());
for (int i = 0; i < results.size(); i++) {
printf("result[%d] = %d\n", i, results[i]);
}
}
public:
string lastSubstring(string s) {
text = s;
memset(dp, -1, sizeof(dp));
dp[text.length() - 1] = 1;
DfsDp(0);
int startIndex = 0;
vector<int> results;
while (startIndex < text.length()) {
results.push_back(startIndex);
startIndex += dp[startIndex];
}
startIndex = 0;
int resultsCount = results.size();
while (1 < results.size()) {
sort(results.begin(), results.end(), [this, startIndex](int x, int y){
return GetText(startIndex + x) > GetText(startIndex + y);
});
//PrintVector(results);
int resultsCount = 1;
for (int i = 1; i < results.size(); i++) {
if (GetText(results[i - 1] + startIndex) == GetText(results[i] + startIndex)) {
resultsCount++;
}
else {
break;
}
}
startIndex++;
while(resultsCount < results.size()){
results.pop_back();
}
}
return text.substr(results[0]);
}
};