Home > OS >  Find the number of substring of a string that satisfy a criteria
Find the number of substring of a string that satisfy a criteria

Time:09-26

Question: Given a string a, find the number of subsegments of the string that contain at least one vowel AND one consonant. For example : input "blue" will have number of subsgments = 1, "hackerrank" will return number of segments = 3 ("ha","cker","rank") each will contain at least one consonant and one vowel.

Here is my code in 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;
}

I run the test cases with code above and it shows 5 out of 15 ouputs are correct. Unfortunately i can't see the input for those incorrect testcases so there is no way i can see the missing logic for my code above to run 100% correct on all cases. Maybe i didn't take into account certain edge cases but i cannot think of any. Is there any flaw of my code above ? Is there any missing cases that i forget to take into account ? Thank you

CodePudding user response:

Try this, I think it will work

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

You did not take into consideration CAPs, special characters & numbers. you check small letter vowels only.

  • Related