I don't know why my code can't meet with time limit(the reverse vowel string problem)


  • 0
    L

    Hi everyone, I really need your help. In problem 345, I wrote my code as follows:

    public class Solution{
        public String reverseVowels(String s){
            int left=0 ;
            int right=s.length()-1;
            while(left<right){
                if(isvowel(s.charAt(left))&&isvowel(s.charAt(right))){
                    
                    s=changetwochar(s,left,right);
                    left++;
                    right--;
                }
                else if(isvowel(s.charAt(left))){
                    right--;
                }
                else if(isvowel(s.charAt(right))){
                    left++;
                }
                else{
                    left++;
                    right--;
                }    
                
            }
            return s;
        }
        
     public String changetwochar(String s, int a, int b){
        	StringBuffer p= new StringBuffer(s);
        	p.setCharAt(a, s.charAt(b));
        	p.setCharAt(b, s.charAt(a));
        	return p.toString();
        }
        
        public boolean isvowel(char c){
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
        }
        
    }
    

  • 0

    @likai28 I just made one edition in your code and got Accepted.

    You just need to construct your StringBuffer once.
    So you can build a StringBuffer and work on it instead of the given string.

    public class Solution{
        public String reverseVowels(String s){
            StringBuffer p= new StringBuffer(s);
            int left=0 ;
            int right= p.length()-1;
            while(left<right){
                if(isvowel(p.charAt(left))&&isvowel(p.charAt(right))){
                    char a = p.charAt(right), b = p.charAt(left);
                    p.setCharAt(left, a);
                    p.setCharAt(right, b);
                    left++;
                    right--;
                }
                else if(isvowel(p.charAt(left))){
                    right--;
                }
                else if(isvowel(p.charAt(right))){
                    left++;
                }
                else{
                    left++;
                    right--;
                }    
                
            }
            return p.toString();
        }
        public boolean isvowel(char c){
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
        }
    }
    

  • 0
    L

    @M.Sayed Thank you very much!!


Log in to reply
 

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