My Java code for Reverse Vowels of a String


  • 0
    J

    public class ReverseVowelsOfAString {

    public String reverseVowels(String s) {
    	if(s==null || s.length()==0){
    		return s;
    	}
    	
    	int l=0;
    	int r=s.length()-1;
    	char[] strArr = s.toCharArray();
    	while(l<r){
    		
    		if(isVowels(strArr[l])){
    			if(isVowels(strArr[r])){
    				char tmp = strArr[r];
    				strArr[r] = strArr[l];
    				strArr[l] = tmp;
    				l++;
    				r--;
    			}else{
    				r--;
    			}
    		}else{
    			l++;
    		}
    	}
    	return new String(strArr);
    }
    
    public boolean isVowels(char c){
    	c = Character.toLowerCase(c);
    	switch (c) {
    		case 'a':
    		case 'e':
    		case 'i':
    		case 'o':
    		case 'u':
    			return true;
    		
    	}
    	return false;
    }
    public static void main(String[] args) {
    	System.out.println(new ReverseVowelsOfAString().reverseVowels("leetcode"));
    }
    

    }


Log in to reply
 

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