Determine if String Halves Are Alike
You are given a string s
of even length. Split this string into two halves of equal lengths, and
let a
be the first half and b
be the second half.
Two strings are alike if they have the same number of vowels ('a'
, 'e'
, 'i'
, 'o'
, 'u'
, 'A'
, 'E'
, 'I'
, 'O'
, 'U'
). Notice that s
contains uppercase and lowercase letters.
Return true
if a
and b
are alike. Otherwise, return false
.
Example 1:
Input: s = "book" Output: true Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
Example 2:
Input: s = "textbook" Output: false Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice.
Example 3:
Input: s = "MerryChristmas" Output: false
Example 4:
Input: s = "AbCdEfGh" Output: true
Constraints:
-
2 <= s.length <= 1000
-
s.length
is even. -
s
consists of uppercase and lowercase letters.
Solution 1:
class Solution {
public boolean halvesAreAlike(String s) {
int i, length = s.length(), mid = s.length()/2;
s = s.toLowerCase();
String chk = "aeiou";
int firstCount=0, secondCount=0;
char ch [] = s.toCharArray();
for(i=0;i<length;i++){
if(i < mid){
if(chk.contains(ch[i]+"")){
firstCount++;
}
}
else{
if(chk.contains(ch[i]+"")){
secondCount++;
}
}
}
if(firstCount == secondCount)
return true;
else
return false;
}
}
Here, we are going to see one of the easiest problem asked in their weekly
contest. In this problem, they clearly mentioned that string length is even.
1) Initially storing vowels in separate string.
2) String contains both uppercase and lowercase. So, convert the whole string
into lowercase [if not just update the vowels string]
3) Convert string to character array, to find all vowels in first half and
second half.
4) Traverse the entire character array,
a) If i is less than mid, then increase firstcount.
b) If i is greater than mid, then increase secondcount.
5) If both firstcount and secondcount are same, return true, Else return
false.
Below we are providing another approach to solve the same problem.
Solution 2:
class Solution {
public boolean halvesAreAlike(String s) {
s = s.toLowerCase();
String s1 = s.substring(0, s.length()/2);
String s2 = s.substring(s.length()/2);
s1 = s1.replaceAll("[^aeiou]","");
s2 = s2.replaceAll("[^aeiou]","");
return s1.length() == s2.length() ? true:false;
}
}
In this solution, we are going to solve using regular expression.
1) Convert string to Lowercase.
2) Separate the string into first half and second half using substring.
3) Remove all consonants[other than vowels] from substring s1, s2.
4) If both substrings are of same length, then return true. Else return false.
Related Posts:
Like us? Please do share with your friends ..!!
Follow us to receive updates instantly.
If you have any feedback/suggestions, leave it in a comment section or contact us through our contact page which will be helpful for us to improve.
Comments
Post a Comment