leetcode -- 345. Reverse Vowels of a String 【双指针 + 逆序的变形】

来源:互联网 发布:周扬青 淘宝 编辑:程序博客网 时间:2024/06/05 17:00

题目

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".


题意


给定一个字符串,只将字符串的原因进行逆序。



分析及解答

  • 双指针 (high ,low)
  • 参照物:
    String vowels = "aeiouAEIOU";

public class Solution {public String reverseVowels(String s) {        char[] array = s.toCharArray();        int low = 0,high = array.length -1;        boolean isLowVow  = false, isHighVow = false;        String vowels = "aeiouAEIOU";        //逆序的核心代码        while(low < high){        isLowVow = (vowels.indexOf(array[low]) != -1);        isHighVow = (vowels.indexOf(array[high]) != -1);        if(isHighVow && isLowVow){        char tmp = array[low];        array[low] = array[high];        array[high] = tmp;        low++;        high--;        }else{        if(!isLowVow){        low++;        }        if(!isHighVow){        high--;        }        }        }        return String.valueOf(array);    }}



原创粉丝点击