Reverse Vowels of a String with time complexity O(n) and space complexity O(n), 6ms


  • 0
    P

    Used two pointers one start and other end, traverse through all elements of string till start is less than end and set flag if we encounter vowels and if both the flagstart and flagend are set then swap characters in array at start and end position.

    class Solution {public String reverseVowels(String s) {
            int start =0,end=s.length()-1,flagStart=0,flagEnd=0;
            char temp;
            char str[]=s.toCharArray();
            while(start<end){
                if(str[start]=='a'||str[start]=='e'||str[start]=='i'||str[start]=='o'||str[start]=='u'
                        ||str[start]=='A'||str[start]=='E'||str[start]=='I'||str[start]=='O'||str[start]=='U')
    
                    flagStart=1;
                if(str[end]=='a'||str[end]=='e'||str[end]=='i'||str[end]=='o'||str[end]=='u'||
                        str[end]=='A'||str[end]=='E'||str[end]=='I'||str[end]=='O'||str[end]=='U')
                    flagEnd=1;
                if(flagStart==1&&flagEnd==1){
                    temp=str[start];
                    str[start]=str[end];
                    str[end]=temp;
                    start++;
                    end--;
                    flagStart=0;
                    flagEnd=0;
                }
                else if(flagStart==1&&flagEnd!=1)
                    end--;
                else if(flagStart!=1&&flagEnd==1)
                    start++;
                else{
                    start++;
                    end--;
                }
            }
    
            return String.valueOf(str);
    
        }
    }
    

Log in to reply
 

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