Leetcode - Reverse Vowels of a String
2016-05-05 19:10
344 查看
Question
Write a function that takes a string as input and reverse only the vowels of a string.Example
Given s = “hello”, return “holle”.Given s = “leetcode”, return “leotcede”.
Java Code
public String reverseVowels(String s) { int len = s.length(); if(len < 2) return s; char[] str = s.toCharArray(); int i = 0; int j = len - 1; //从数组的两端往中间搜索 while(i < j) { if(isVowel(str[i])) { if(isVowel(str[j])) swap(str, i++, j--);//如果两者都是元音字母,交换之且两个指针都移向下一位 else j--;//j指针一直遍历直到指向元音字母 }else i++;//i指针一直遍历直到指向元音字母 } return new String(str); } //判断一个字符是否为元音字母 public boolean isVowel(char ch) { switch(ch) { case 'a' : case 'e' : case 'i' : case 'o' : case 'u' : case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : return true; default : return false; } } //交换数组中的两个元素 public void swap(char[] str, int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; }
相关文章推荐
- linux添加和增大交换分区(swap)的方法
- Shell脚本实现监控swap空间使用情况和查看占用swap的进程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- centos linux添加1G的swap分区
- 调整swap分区大小
- 查看哪些进程使用swap脚本
- 安装oracle时swap过小安装失败
- 扩大swap分区的命令
- leetcode----Longest Substring Without Repeating Characters
- 如何合理设置Linux的swap分区
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap