求最长连续元音字母字符串的长度

题目描述:给出字符串,求其中的最长元音字母子字符串的长度。

e.g: 输入的字符串为abbaacbioueabba, 由于元音字母是'a', 'A', 'e',  'E', 'i', 'I', 'o', 'O', 'u', 'U'这十个,在给出的字符串中,包含这十个字母的最长的子字符串的长度为5, 即iouea,故输出为5.

----------------------------------------------------------------------分隔线-------------------------------------------------------------------------

 其实这道题目与求最大子数组的和十分相似。

我们可以设一个count用以返回符合题目条件的长度,用一个暂时长度来记录遇到元音字母时该子字符串的长度,记为temp,那么当遇到一个元音字母时,temp的长度就+1,如果此时的temp比count要大的话,更新count的值。如果遇到的字符不属于元音字母时,temp的值归零,这样就可以删除temp的记忆,即在遇到下一个元音字母时,temp以前的记录不会保留。

实现代码如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = "";
        while(sc.hasNext()) {
            str = sc.nextLine();
            int res = findLen(str);
            System.out.println(res);
        }
    }
    
    public static int findLen(String str) {
        char[] ch = str.toCharArray();
        int count = 0, temp = 0;
        int len = ch.length;
        for(int i = 0; i < len; i++) {
            if(ch[i] == 'a' || ch[i] == 'e' || ch[i] == 'i' || ch[i] == 'o' || ch[i] == 'u' ||
                    ch[i] == 'A' || ch[i] == 'E' || ch[i] == 'I' || ch[i] == 'O' || ch[i] == 'U') {
                temp++;
                count = count > temp ? count : temp;
            }else
                temp = 0;
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/WakingShaw/p/13185585.html