leetcode 345 Reverse Vowels of a String

xiaoxiao2021-02-28  122

1. 题目分析

  题目描述: 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”.

Note: The vowels does not include the letter “y”.

  题目含义:只对string中的元音字符进行交换,英语中原因包括a、e、i、o、u。   题目分析:使用二分法的方法,使用两个指针分别从两端进行查找,直到均查找到符合条件的字符后进行交换。在题目中,不要忘记对元音的判断要包含大写和小写两种情况。

2. 题目解答–cpp

class Solution { public: // 判定传入的字符是否为元音 bool isVowels(char t) { char temp[] = "aeiouAEIOU"; for (int i = 0; i < 10; i++) { if(t == temp[i]) { return true; } } return false; } string reverseVowels(string s) { char t; int front = 0; int end = s.size()-1; while (front < end) { // 只有两个指针指向的字符均为元音时才进行交换 if (isVowels(s[front]) && isVowels(s[end])) { t = s[front]; s[front] = s[end]; s[end] = t; front++; end--; } else { // front从当前位置开始向后查找,直到找到元音为止 if (!isVowels(s[front])) { front++; } // end从当前位置开始向前查找,直到找到元音为止 if (!isVowels(s[end])) { end--; } } } return s; } };
转载请注明原文地址: https://www.6miu.com/read-72860.html

最新回复(0)