[LeetCode] Reverse Vowels of a String
来源:互联网 发布:mysql 配置优化 编辑:程序博客网 时间:2024/06/12 01:25
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”.
解题思路
双指针,一个往前移动,一个往后移动,找到元音字母时则交换。
实现代码
// Runtime: 12 mspublic class Solution { private static final String STR = "aeiouAEIOU"; private static final Set<Character> VOWELS = new HashSet<Character>(STR.length()); static { for (int i = 0; i < STR.length(); i++) { VOWELS.add(STR.charAt(i)); } } public String reverseVowels(String s) { StringBuilder sb = new StringBuilder(s); int left = 0; int right = sb.length() - 1; while (left < right) { while (left < right && !isVowels(sb.charAt(left))) { ++left; } while (left < right && !isVowels(sb.charAt(right))) { --right; } char temp = sb.charAt(left); sb.setCharAt(left++, sb.charAt(right)); sb.setCharAt(right--, temp); } return sb.toString(); } private boolean isVowels(char ch) { return VOWELS.contains(ch); }}
0 0
- Leetcode Reverse Vowels of a String 345
- LeetCode 345. Reverse Vowels of a String
- LeetCode - Reverse Vowels of a String
- leetcode-345. Reverse Vowels of a String
- 【LeetCode-345】Reverse Vowels of a String
- #leetcode#345. Reverse Vowels of a String
- leetcode 345Reverse vowels of a string
- [leetcode] 345. Reverse Vowels of a String
- Leetcode:345. Reverse Vowels of a String
- LeetCode *** 345. Reverse Vowels of a String
- leetcode 345:Reverse Vowels of a String
- leetcode笔记:Reverse Vowels of a String
- LeetCode 345 Reverse Vowels of a String
- LeetCode:Reverse Vowels of a String
- LeetCode.345. Reverse Vowels of a String
- LeetCode 345 Reverse Vowels of a String
- Leetcode - Reverse Vowels of a String
- LeetCode 345. Reverse Vowels of a String
- Web前端知识体系
- MySQL
- node+Express开发
- 关于sql server 安装程序在运行 Windows Installer 文件时遇到错误。
- 杭电 2049 (错排,递归,组合)
- [LeetCode] Reverse Vowels of a String
- 异或树
- tcp套接字编程模型
- 杭电1023 train problem2
- 04.SpringMVC 初始化 - DispatcherServlet
- Android存储(读取)之缓存CachesDir存储
- Hadoop HDFS常用文件操作命令
- 吴恩达机器学习笔记_第五周
- LeetCode LRU Cache