TreeviewCopyright © aleen42 all right reserved, powered by aleen42

345. 反转字符串中的元音字母

https://leetcode-cn.com/problems/reverse-vowels-of-a-string/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-25 17:39:22
 * @Description: https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
 * @FilePath: \leetcode-googtech\#345. Reverse Vowels of a String\Solution.java
 */ 
class Solution {
    // 双指针法
    public String reverseVowels(String s) {
        // 声明用于交换数组元素的中间变量
        char temp;
        // 将字符串转换为数组
        char[] str = s.toCharArray();
        // 声明用于匹配的元音字符串
        String letter = "aeuioAEIUO";
        // 初始化头指针和尾指针
        int first = 0,last = s.length() - 1;
        // 遍历数组中的元素
        while(first < last){
            // 判断当前元素是否为元音
            // 若为元音则反转字符串中的元音字母,然后同时移动头和尾部指针.反之继续移动头或尾部指针
            if(letter.indexOf(str[first])!= -1  && letter.indexOf(str[last])!= -1){
                temp = str[first];
                str[first] = str[last];
                str[last] = temp;
                first++;
                last--;
            }else if(letter.indexOf(str[first])!= -1){
                last--;
            }else if(letter.indexOf(str[last])!= -1){
                first++;
            }else{
                first++;
                last--;
            }
        }
        // 返回结果
        return new String(str);
    }
}

Python

'''
@Author: Goog Tech
@Date: 2020-07-25 17:39:29
@Description: https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
@FilePath: \leetcode-googtech\#345. Reverse Vowels of a String\Solution.py
'''
class Solution(object):
    # 双指针法
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 声明用于匹配的元音列表
        patterns = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        # 初始化头部和尾部指针
        left = 0
        right = len(s) - 1
        # 将字符串转换为列表
        s = list(s)
        # 遍历列表
        while left < right:
            # 从左向右移动左指针,获取为元音字符的下标值
            while left < right and s[left] not in patterns:
                left = left + 1
            # 从右向左移动右指针,获取元音字符的下标值
            while right > left and s[right] not in patterns:
                right = right - 1
            # 反转列表中的元音字符并且继续移动头和尾部指针
            s[left], s[right] = s[right], s[left]
            left = left + 1
            right = right - 1
        # 返回结果
        return ''.join(s)


"""
Python join() 方法用于将序列(sequence)中的元素以指定的字符连接生成一个新的字符串
join()方法语法: str.join(sequence)

str = "-";
seq = ("a", "b", "c");
print str.join( seq );
"""
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""