【问题标题】:Find the number of substring of a string that satisfy a criteria查找满足条件的字符串的子字符串数
【发布时间】:2021-11-18 16:21:12
【问题描述】:

问题: 给定一个字符串 a,找出字符串中至少包含一个元音和一个辅音的子段数。例如:输入“blue”将有子句数 = 1,“hackerrank”将返回段数 = 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% 正确运行。也许我没有考虑到某些边缘情况,但我想不出任何。我上面的代码有什么缺陷吗?有没有我忘记考虑的遗漏案例?谢谢

【问题讨论】:

  • @kungho 您没有考虑大写字母、特殊字符和数字。你只检查小写元音。所以例如“blUE”不起作用

标签: java string algorithm testing substring


【解决方案1】:

试试这个,我想它会起作用的

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;
}

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

【讨论】:

  • 是的,我应该考虑大写字母,但是考虑特殊字符和数字将如何改变我的代码逻辑,因为我的 for 循环在我检查时没有排除其中任何一个对于条件
  • 'a1' 不满足您的条件,但它会从您的函数返回 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 2021-11-20
相关资源
最近更新 更多