LeetCode //C - 345. Reverse Vowels of a String

2023-12-16 22:36:17

345. Reverse Vowels of a String

Given a string s, reverse only all the vowels in the string and return it.

The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lower and upper cases, more than once.
?

Example 1:

Input: s = “hello”
Output: “holle”

Example 2:

Input: s = “leetcode”
Output: “leotcede”

Constraints:
  • 1 < = s . l e n g t h < = 3 ? 1 0 5 1 <= s.length <= 3 * 10^5 1<=s.length<=3?105
  • s consist of printable ASCII characters.

From: LeetCode
Link: 345. Reverse Vowels of a String


Solution:

Ideas:
  1. Check for Vowels: Create a function or a way to check if a character is a vowel.
  2. Two Pointer Approach: Use two pointers, one starting at the beginning of the string and the other at the end. Move these pointers towards each other.
  3. Swap Vowels: When both pointers point to vowels, swap these characters.
  4. Continue Until Pointers Meet: Keep moving the pointers and swapping vowels until the pointers meet or cross each other.
Code:
// Function to check if a character is a vowel
bool isVowel(char ch) {
    char vowels[] = "aeiouAEIOU";
    for (int i = 0; i < 10; i++) {
        if (ch == vowels[i]) {
            return true;
        }
    }
    return false;
}

// Function to reverse vowels in a string
char* reverseVowels(char* s) {
    int i = 0;
    int j = strlen(s) - 1;

    while (i < j) {
        // Find the next vowel from the start
        while (i < j && !isVowel(s[i])) {
            i++;
        }

        // Find the next vowel from the end
        while (i < j && !isVowel(s[j])) {
            j--;
        }

        // Swap the vowels
        if (i < j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;

            i++;
            j--;
        }
    }

    return s;
}

文章来源:https://blog.csdn.net/navicheung/article/details/135038055
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。