查找满足条件的字符串的子串数

Find the number of substring of a string that satisfy a criteria

问题: 给定一个字符串 a,找到该字符串中至少包含一个元音和一个辅音的子片段的数量。例如:输入“blue”将有 number of subsgments = 1,“hackerrank”将 return number of segments = 3 ("ha","cker","rank") 每个将包含至少一个辅音和一个元音。

这是我在 Java

中的代码
public static int segments(String password){
      int numbersegments = 0;
      int vowel = 0;
      int consonant = 0;
      for(int index = 0; index < password.length();index++){
            if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
                    password.charAt(index) == 'i' || password.charAt(index) == 'u'
                    || password.charAt(index) == 'o'    ){
                  vowel++;
            }
            else
                consonant++;
            if(vowel >= 1 && consonant >= 1){
                numbersegments++;
                vowel = 0;
                consonant = 0;

            }
      }
      return numbersegments;
}

我 运行 带有上面代码的测试用例,它显示 15 个输出中有 5 个是正确的。不幸的是,我看不到那些不正确的测试用例的输入,所以我无法看到我上面的代码缺少的逻辑,运行 在所有情况下都是 100% 正确的。也许我没有考虑到某些边缘情况,但我想不出任何。我上面的代码有什么缺陷吗?有没有我忘记考虑的遗漏案例?谢谢

试试这个,我认为它会起作用

public static int segments(String password){
  int numbersegments = 0;
  int vowel = 0;
  int consonant = 0;

  password = password.toLowerCase(); 

  for(int index = 0; index < password.length();index++){
        if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
                password.charAt(index) == 'i' || password.charAt(index) == 'u'
                || password.charAt(index) == 'o'  ){
              vowel++;
        }
        else if(password.charAt(index)>='a' && password.charAt(index)<='z')
            consonant++;

        if(vowel >= 1 && consonant >= 1){
            numbersegments++;
            vowel = 0;
            consonant = 0;
        }
  }
  return numbersegments;
}

您没有考虑大写字母、特殊字符和数字。你只检查小写字母元音。