My Simple Java Solution


  • 0
    E

    So I get the positions and the corresponding vowels in 2 different arraylists and then reverse the vowel arraylist. When reconstructing the String I just place the replaced vowels in their respective positions by getting the indexes from the pos arraylist.

    public class Solution {
        public String reverseVowels(String s) {
            StringBuilder sb=new StringBuilder();
            ArrayList<Character>c=new ArrayList<Character>();
            ArrayList<Integer>pos=new ArrayList<Integer>();
            String v="aeiouAEIOU";
            for(int i=0;i<s.length();i++){
                char ch=s.charAt(i);
                if(v.contains(ch+"")){
                    pos.add(i);
                    c.add(ch);
                }
            }
            Collections.reverse(c);
            int x=0,p=-1;
            if(pos.size()>0){
               p=pos.get(x); 
            }
            
            for(int i=0;i<s.length();i++){
                if(p==i){
                    sb.append(c.get(x));
                    x++;
                    if(x<pos.size()){
                        p=pos.get(x);
                    }
                    
                }
                else{
                    sb.append(s.charAt(i));
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.