加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

【LeetCode】345. Reverse Vowels of a String

发布时间:2020-12-15 07:31:36 所属栏目:Java 来源:网络整理
导读:Difficulty: Easy ?More: 【目录】LeetCode Java实现 Description https://leetcode.com/problems/reverse-vowels-of-a-string/ Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello"Output:

Difficulty: Easy

?More:【目录】LeetCode Java实现

Description

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

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

Example 1:

Input: "hello"
Output: "holle" 

Example 2:

Input: "leetcode"
Output: "leotcede"

?

Intuition

Using two pointers.

?

Solution

    private final static HashSet<Character> vowels = new HashSet<Character>        (
        Arrays.asList(‘a‘,‘e‘,‘i‘,‘o‘,‘u‘,‘A‘,‘E‘,‘I‘,‘O‘,‘U‘));
    public String reverseVowels(String s) {
        if(s==null || s.length()<=0)
            return s;
        int i=0,j=s.length()-1;
        char[] chars = new char[s.length()];
        while(i<=j){
            char ci=s.charAt(i);
            char cj=s.charAt(j);
            if(!vowels.contains(ci))
                chars[i++]=ci;
            else if(!vowels.contains(cj))
                chars[j--]=cj;
            else{
                chars[i++]=cj;
                chars[j--]=ci;
            }
        }
        return String.valueOf(chars);
    }

  

Complexity

Time complexity :?O(n)

Space complexity :??O(1)

What I‘ve learned

1.The use of two pointers.

?

?More:【目录】LeetCode Java实现

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读