leetcode_345 Reverse Vowels of a String

来源:互联网 发布:muji.it 编辑:程序博客网 时间:2024/05/21 19:41
  • 题目分析:

    给定一个字符串,把字符串中的元音字符转置

  • 解题思路:

    1)定义两个指标i,j,分别指向字符串最前端和字符串最尾端;

    2)遍历字符串,判断字符串中对应位置字符是否为元音字符,如果是元音字符,停止遍历,然后在另一方向找到对应位置的元音字符位置,找到后,将两个位置字符进行交换,然后继续遍历,直到遍历结束。

    3)遍历方式类似于快速排序中的遍历调整位置。

  • 实现程序

    • C++版本

      class Solution {    public:        void my_swap(char *c1, char *c2)        {            char temp = *c1;            *c1 = *c2;            *c2 = temp;        }        string reverseVowels(string s)        {            int i = 0;            int j = s.length() - 1;            while (i < j)            {                while (i < j && (s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u')                             && (s[i] != 'A' && s[i] != 'E' && s[i] != 'I' && s[i] != 'O' && s[i] != 'U'))                    i++;                while (i < j && (s[j] != 'a' && s[j] != 'e' && s[j] != 'i' && s[j] != 'o' && s[j] != 'u')                             && (s[j] != 'A' && s[j] != 'E' && s[j] != 'I' && s[j] != 'O' && s[j] != 'U'))                    j--;                my_swap(&s[i], &s[j]);                i++;                j--;            }            return s;        }   };
    • Java版本

      public boolean isVowels(char c){        // 将字符c同一转换为小写字符        c = Character.toLowerCase(c);        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')            return true;        return false;    }    public String reverseVowels(String s){        int i = 0;        int j = s.length() - 1;        char[] ss = s.toCharArray();        char temp;        while (i < j){            while (i < j && (!isVowels(ss[i]))){                i++;            }            while (i < j && (!isVowels(ss[j]))){                j--;            }            // 交换两个ss[i]与ss[j]            temp = ss[i];            ss[i] = ss[j];            ss[j] = temp;            i++;            j--;        }        return new String(ss);    }
0 0
原创粉丝点击