Write a function that takes a string as input and reverses only the vowels of a string.
Example 1:
Input: "hello" Output: "holle"
Approach
Java
import java.util.Arrays;import java.util.List;public class ReverseVowels {public static void main(String[] args) {String str = "hello";String revStr = reverseVowels(str);System.out.println(revStr);}// method to reverse the vowels in stringpublic static String reverseVowels(String s) {Character[] vovels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };List<Character> v = Arrays.asList(vovels);char[] st = s.toCharArray();int l = s.length();int high = l - 1;int low = 0;// iterate till low<=high// two pointer approachwhile (low <= high) {while (!v.contains(s.charAt(low)) && low < high) {low++;}while (!v.contains(s.charAt(high)) && low < high) {high--;}if (low < high) {st[low] = s.charAt(high);st[high] = s.charAt(low);}low++;high--;}return new String(st);}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for//vowel or notbool 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 reverse the vowels in stringstring reverseVowels(string s){int l = s.size();int high = l - 1;int low = 0;// iterate till low<=high// two pointer approachwhile (low <= high) {while (!isVowel(s[low]) && low < high) {low++;}while (!isVowel(s[high]) && low < high) {high--;}if (low < high) {char temp=s[low];s[low]=s[high];s[high]=temp;}low++;high--;}return s;}int main(){string str = "hello";string revStr = reverseVowels(str);cout<<revStr;return 0;}
No comments:
Post a Comment