LeetCode-345.Reverse Vowels of a String

来源:互联网 发布:php文章分页 编辑:程序博客网 时间:2024/04/29 02:57

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:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

一开始不理解题意

目标就是前后交换元音字符

string reverseVowels(string s)    {        int i = 0, j = s.length() - 1;    bool l, r;    string vowels = "aeiouAEIOU";    char c;    while (i < j)    {    l = vowels.find(s[i]) != string::npos;    r = vowels.find(s[j]) != string::npos;    if (l&&r)    {    c = s[i];    s[i] = s[j];    s[j] = c;    i++;    j--;    }    else    {    if (!l)    i++;    if (!r)    j--;    }    }    return s;    }

 string reverseVowels(string s)    {        int i = 0, j = s.length() - 1;    char c;    string vowels = "aeiouAEIOU";    while (i < j)    {    while (i < j&&vowels.find(s[i]) == string::npos)    i++;    while (i < j&&vowels.find(s[j]) == string::npos)    j--;    if (i<j)    {    c = s[i];    s[i] = s[j];    s[j] = c;    i++;    j--;    }    }    return s;    }


0 0
原创粉丝点击