Leetcode 5069. 按字典序排在最后的子串 (150周赛)

5069. 按字典序排在最后的子串

给你一个字符串 s,找出它的所有子串并按字典序排列,返回排在最后的那个子串。

示例 1:

输入:"abab"
输出:"bab"
解释:我们可以找出 7 个子串 ["a", "ab", "aba", "abab", "b", "ba", "bab"]。按字典序排在最后的子串是 "bab"。

示例 2:

输入:"leetcode"
输出:"tcode"

提示:

  1. 1 <= s.length <= 10^5
  2. s 仅含有小写英文字符

 注意的是要保证内存消耗和时间消耗尽量小。


class Solution {
public:
	bool judge(string a, string b)
	{
		int N = min(a.size(), b.size());
		int i = 0;
		//cout << a[0] << ' ' << a.size();
		while (a[i] == b[i] && (++i) < N);
		if (i == N)
		{
			if (a.size() > b.size())
				return 1;
			else
				return 0;
		}
		if (a[i] > b[i])
			return 1;
		else
			return 0;
	}
	string lastSubstring(string s) {
		char max = 0;

		int n = 0;
		for (int i = 0; i < s.size(); i++)
		{
			if (s[i] > max)
			{
				max = s[i];
			}
		}
		int k = s.find(max), k_max = 0, xiabiao;
		string res;
        string p(s);
		while (k != -1)
		{
			s[k] = '*';
			int add = 1;
			while (s[k + add] == max)
			{
				s[k + add] = '*';
				add++;
			}
			if (add - 1 > k_max)
			{
				k_max = add - 1;
				xiabiao = k;
				res  = p.substr(k, s.size());
			}
			else if (add - 1 == k_max)
			{
				string b = p.substr(k, s.size());
				res = judge(b, res) ? b : res;
			}
			k = s.find(max);
		}
		return res;
	}
};
发布了104 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Yanpr919/article/details/99707258
今日推荐