1. 程式人生 > >LeetCode#345. Reverse Vowels of a String

LeetCode#345. Reverse Vowels of a String

  • 題目:反轉字串中的母音字母
  • 難度:Easy
  • 思路:借鑑二分查詢的思想,分別從前後進行查詢,找到母音字母,就交換
  • 程式碼:
public class Solution {
    public String reverseVowels(String s) {
        if(s == null || s.equals("")){
            return s;
        }
        String vowels = "aeouiAEOUI";
        StringBuilder sb = new StringBuilder(s);
        int
len = s.length(); int left = 0; int right = len-1; while(left < right){ char ch1 = sb.charAt(left); char ch2 = sb.charAt(right); while(left < right && vowels.indexOf(ch1) == -1){ left++; ch1 = sb.charAt(left
); } while(left < right && vowels.indexOf(ch2) == -1){ right--; ch2 = sb.charAt(right); } if(left < right){ sb.replace(left,left+1,String.valueOf(ch2)); sb.replace(right,right
+1,String.valueOf(ch1)); } left++; right--; } return sb.toString(); } }