Two strings are alike if they have the same number of vowels
Given a string of even length. Split this string into two halves of equal lengths.
Example 1:
Input: s = "book" Output: Alike
Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
Approach:
Java
import java.util.Arrays;
import java.util.List;
public class HalvesAreAlike {
static Character[] vovels = { 'a', 'e', 'i', 'o',
'u', 'A', 'E', 'I', 'O', 'U' };
public static void main(String[] args) {
String s = "book";
System.out.println(halvesAreAlike(s));
}
private static boolean halvesAreAlike(String s) {
List<Character> v = Arrays.asList(vovels);
int length = s.length();
String left = s.substring(0, length / 2);
String right = s.substring(length / 2, length);
int lV = 0;
int rV = 0;
for (int i = 0; i < length / 2; i++) {
if (v.contains(left.charAt(i))) {
lV++;
}
if (v.contains(right.charAt(i))) {
rV++;
}
}
if (lV == rV)
return true;
return false;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to check the
//character is vowel or not
bool isVowel(char ch)
{
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
return true;
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
return true;
return false;
}
//function to check the halves are alike
//or not
bool halvesAreAlike(string s)
{
int n=s.size();
int half=0;
for(int i=0;i<s.size()/2;i++)
{
if(isVowel(s[i]))
half++;
}
for(int i=s.size()/2;i<s.size();i++)
{
if(isVowel(s[i]))
half--;
}
if(half==0)
return true;
return false;
}
int main()
{
//string length must be
//even
string str="book";
if(halvesAreAlike(str))
cout<<"Alike\n";
else
cout<<"Not alike\n";
return 0;
}
No comments:
Post a Comment