Reverse Vowels of a String | String Problem | LeetCode 345

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a String, write a program to reverse only the vowels of an input string. Implement the problem in O(1) extra memory.

Example 

Reverse Vowels of a String

Input :- "hello"
Output :- "holle"
Input :- "morning"
Output :- "mirnong"

Solution

This problem can be solved in following steps :-

  1. Create the character array from the input String.
  2. Create three variables first pointing to index 0, second pointing to last index (n-1, where n is the length of an array) and temp.
  3. Move the first variable to right, if the character at first is not a vowel.
  4. Move the second variable to left, if the character at second is not a vowel.
  5. If character at both first and second variables are vowels then copy the character at first variable to temp, the character at second variable to first and character at temp variable to second.
  6. Repeat steps 3, 4 and 5, until first is less than second.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String result = main.reverseVowels("morning");
		System.out.print(result);
	}
	
	/* Solution */
	public String reverseVowels(String s) {
        
        char[] array = s.toCharArray();
        
        boolean isStartPresent = false;
        boolean isEndPresent = false;
        
        int start = 0, end = array.length-1;
        char temp;
        while(start < end){
            
            if(checkVowel(array[start])){
                isStartPresent = true;
            }else {
                start++;
            }
            
            if(checkVowel(array[end])){
                isEndPresent = true;
            }else {
                end--;
            }
            
            if(isEndPresent && isStartPresent){
                temp = array[end];
                array[end] = array[start];
                array[start] = temp;                
                isStartPresent = false;
                isEndPresent = false;
                start++;
                end--;
            }   
        }
        return String.valueOf(array);        
    }
    
    public boolean checkVowel(char value){        
        if(value != 'a' && value != 'e' && value != 'i' && value != 'o' && value != 'u'
           &&
           value != 'A' && value != 'E' && value != 'I' && value != 'O' && value != 'U'){
            return false;
        }
        return true;        
    }
}

Result

gninrom

Similar Post

  1. Count and Say
  2. Reverse only Letters of a String
  3. Shifting Letters of a String

That’s all for Reverse Vowels of a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.