Algorithm-Quick Sorting Thought Reverses Vowels in Strings

Algorithm-Quick sorting of ideas to reverse the vowels in a string

Reverse the vowels in the string

345. Reverse vowels in a string

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入: "hello"
输出: "holle"
示例 2:

输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。

Everyone knows the fast queue, so I won't say much. The main body seems to have nothing to do with the fast queue, but in fact it is quite relevant.
Quick row selects the pivot yuan as the exchange condition, and we can also use the vowel letter as the exchange condition.

    public String reverseVowels(String s) {
        if(s==null||s.length()<2){
            return s;
        }
        char cs[]=s.toCharArray();
        quickSwap(cs,0,cs.length-1);
        return new String(cs);
    }

    public void quickSwap(char[] cs,int left,int right){
        while(left<right){
            while(left<right&&!suit(cs[right])){
                right--;
            }
            while(left<right&&!suit(cs[left])){
                left++;
            }
            if(left<right){
                swap(cs,left,right);
            }
            left++;
            right--;
        }
    }

    private boolean suit(char c){
        return c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U';
    }

    private void swap(char[] cs,int i,int j){
        char temp=cs[i];
        cs[i]=cs[j];
        cs[j]=temp;
    }

Guess you like

Origin blog.csdn.net/qq_23594799/article/details/105463157