LeetCode-in-Java

3775. Reverse Words With Same Vowel Count

Medium

You are given a string s consisting of lowercase English words, each separated by a single space.

Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged.

Return the resulting string.

Vowels are 'a', 'e', 'i', 'o', and 'u'.

Example 1:

Input: s = “cat and mice”

Output: “cat dna mice”

Explanation:

Example 2:

Input: s = “book is nice”

Output: “book is ecin”

Explanation:

Example 3:

Input: s = “banana healthy”

Output: “banana healthy”

Explanation:

Constraints:

Solution

public class Solution {
    public String reverseWords(String s) {
        char[] wrd = s.toCharArray();
        String vowels = "aeiou";
        int left = 0;
        int right = 0;
        int firstWrd = 0;
        int anotherWrd = 0;
        while (left < wrd.length) {
            right = left;
            anotherWrd = 0;
            while (right < wrd.length && wrd[right] != ' ') {
                if (vowels.indexOf(wrd[right]) != -1) {
                    if (left == 0) {
                        firstWrd++;
                    } else {
                        anotherWrd++;
                    }
                }
                right++;
            }
            if (left != 0 && anotherWrd == firstWrd) {
                int l = left;
                int r = right - 1;
                while (l < r) {
                    char temp = wrd[r];
                    wrd[r--] = wrd[l];
                    wrd[l++] = temp;
                }
            }
            left = right + 1;
        }
        return new String(wrd);
    }
}