1648. max substring
Given a string s, return the last substring of s in lexicographical order.
Example
Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"].
The lexicographically maximum substring is "bab".
Example 2:
Input: "baca"
Output: "ca"
Notice
1 <= s.length <= 4 * 10^4
s contains only lowercase English letters.
Input test data (one parameter per line)How to understand a testcase?
解法1:
首先我们要认识到一点,那就是最后的结果一定是以s字符串中某个最大的字符开始到结尾。注意s里面最大的字符可能出现很多次,我们只需遍历这些最大字符出现的地方i,找到s.substr(i)的最大值即可。
举例:
1)s = "cabcba",result = "cba"。
2)s = “cbacab”,result = "cbacab"。
3)s = "cabcbaab", result = "cbaab"。
4)s = "cbacabab",result = "cbacabab“。
class Solution {
public:
/**
* @param s: the matrix
* @return: the last substring of s in lexicographical order
*/
string maxSubstring(string &s) {
int len = s.size();
if (len == 0) return "";
string result = "";
char largestChar = 'a';
for (int i = 0; i < len; ++i) {
if (largestChar < s[i]) largestChar = s[i];
}
for (int i = 0; i < len; ++i) {
if (s[i] == largestChar) {
result = max(result, s.substr(i));
}
}
return result;
}
};
本文介绍如何解决给定字符串问题,即找出按字典序最后的子串。通过遍历最大字符并寻找其出现位置,找到s中的最长字典序子串。理解并实现一种高效的解法,适用于长度小于40000的英文小写字母字符串。
337

被折叠的 条评论
为什么被折叠?



