LeetCode1839. 所有元音按顺序排布的最长子字符串

LeetCode

LeetCode1839. 所有元音按顺序排布的最长子字符串_第1张图片 

我的思路: 有点像滑动窗口 

  (  没注意看题目条件,都是元音,而自己写的任何字符都能判断 ,麻烦了一点 )

 

    1.单独定义一个元音字符串用于判断。

    2.‘a’ 是判断美丽字符串的入口, 先在word中找到 ‘ a ’,

    3. 从 ' a '该 下标向后在word中找连续的 元音字母    

   4.找到美丽字符串和之前的相比,取字符串个数最大值

class Solution {
public:
    int longestBeautifulSubstring(string word) 
    {
        int size = word.size();

	if (size < 5) //如果个数 < 5 肯定不是
		return 0;

	string dict = "aeiou";
	int Maxret = 0;
	int i = 0;

	while (i <= (size - 5)) //如果i前面判断过后字符个数 < 5 也不会有美丽字符串了
	{
		if (word[i] == 'a') //判断美丽字符串的入口
		{   
			int index = i + 1; //从第二个字符开始向后判断
			
			int j = 0;

			while(j < 5) // j用于指向 元音字母
			{
				if (word[index] == dict[j]) //后序有元音字母 
				{
					if (index < size) //未越界,index后移
					{
						index++;
					}
					else              //越界跳出循环
					{
						break;
					}
					
				} 
				else                 //后序的元音字母可能是 j指向的下一个
				{
					j++;
					if (j == 5) //防止越界  
						break;

					if (word[index] == dict[j]) //和之前的元音字母连起来了是连续的
						continue;
					else
						break;
				}
			}

			if (j == 5) //找到了 美丽字符串进行计算
			{
				int temp = index - i;
				if (temp > Maxret)
					Maxret = temp;

			}

			i = index; //不管是否找到美丽字符串 [ i , index]我们已经证实过了
	
		}
		else //找不到'a'入口,继续找
		{
			i++;
			continue;
		}
	}

	return Maxret;
    }
};

 

比较好的思路:

1.首先如果数组长度小于5的话,不可能满足美丽的定义,将这种情况提前排除
2.遍历时分了几种情况判断:
- 如果当前字符比上一个不小(顺序意义),那么当前子串长度+1
- 如果当前字符比上一个大,那么子串中元音字母种类+1
- 如果当前字符比上一个小,那么肯定当前字串不美丽,以当前字符为首继续进行遍历
3.如果当前子字符串没有以a开头的话,那么在进行下一个子字符串开始遍历之前,元音种类一定不会达到5,所以只要判断种类即可
4.当元音种类为5的时候,持续维护更新最终结果,取出最大值即可


作者:SweetpepperJ
链接:https://leetcode-cn.com/problems/longest-substring-of-all-vowels-in-order/solution/bi-da-xiao-by-sweetpepperj-gdlt/
来源:力扣(LeetCode)
 

class Solution {
public:
    int longestBeautifulSubstring(string word) {
		if (word.size()<5)return 0;
		int res=0;
		int rlen=1;
		int vowel=1;
		for(int i=1;i=word[i-1])
              rlen++;

			if(word[i]>word[i-1])    妙呀
              vowel++;

			if(word[i]res?rlen:res;
            }

		}
		return res;
    }
};

你可能感兴趣的:(力扣刷题,leetcode,c++,后端)