当前位置:网站首页>LeetCode - 345. The reversal in the string vowels

LeetCode - 345. The reversal in the string vowels

2022-08-06 07:55:12Peas Erguotou

反转字符串中的元音字母

题目

给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串.

元音字母包括 ‘a’、‘e’、‘i’、‘o’、‘u’,且可能以大小写两种形式出现.

思路

没有什么难度,Very simple array judgment exchange.

代码

class Solution {
    
    public String reverseVowels(String s) {
    
        int length = s.length();
        char[] word = s.toCharArray();
        int left = 0;
        int right = length-1;
        int flag_left=0;	//From the left, the marks of the original letters were found
        int flag_right=0;  	//From the right, the mark of the original letter was found 
        while (left<right)
        {
    
            if (!check(word[left]))
                ++left;
            else
                flag_left=1;
            if (!check(word[right]))
                --right;
            else
                flag_right=1;
            if (flag_left==1 && flag_right==1)
            {
    
            	// swap two letters
                char temp=' ';
                temp=word[left];
                word[left]=word[right];
                word[right]=temp;
                // Because after the exchange, the two positions must be the original letters,So change the subscript directly
                ++left;
                --right;
                // 交换之后,It is necessary to clear the flag waiting for the exchange
                flag_left=0;
                flag_right=0;
            }
        }
        return String.valueOf(word);
    }

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

结果

在这里插入图片描述
简单题,I didn't know why at the time,没有AC掉.

原网站

版权声明
本文为[Peas Erguotou]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/218/202208060745383361.html

随机推荐