Skip to content

3856. Trim Trailing Vowels

Description

You are given a string s that consists of lowercase English letters.

Return the string obtained by removing all trailing vowels from s.

The vowels consist of the characters 'a', 'e', 'i', 'o', and 'u'.

Β 

Example 1:

Input: s = "idea"

Output: "id"

Explanation:

Removing "idea", we obtain the string "id".

Example 2:

Input: s = "day"

Output: "day"

Explanation:

There are no trailing vowels in the string "day".

Example 3:

Input: s = "aeiou"

Output: ""

Explanation:

Removing "aeiou", we obtain the string "".

Β 

Constraints:

  • 1 <= s.length <= 100
  • s consists of only lowercase English letters.

Solutions

Solution 1: Reverse Traversal

We traverse the string from the end in reverse order until we encounter the first non-vowel character. Then we return the substring from the beginning of the string up to that position.

The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).

1
2
3
4
5
6
class Solution:
    def trimTrailingVowels(self, s: str) -> str:
        i = len(s) - 1
        while i >= 0 and s[i] in "aeiou":
            i -= 1
        return s[: i + 1]
1
2
3
4
5
6
7
8
9
class Solution {
    public String trimTrailingVowels(String s) {
        int i = s.length() - 1;
        while (i >= 0 && "aeiou".indexOf(s.charAt(i)) != -1) {
            i--;
        }
        return s.substring(0, i + 1);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    string trimTrailingVowels(string s) {
        int i = s.size() - 1;
        while (i >= 0 && string("aeiou").find(s[i]) != string::npos) {
            i--;
        }
        return s.substr(0, i + 1);
    }
};
1
2
3
4
5
6
7
func trimTrailingVowels(s string) string {
    i := len(s) - 1
    for i >= 0 && strings.IndexByte("aeiou", s[i]) != -1 {
        i--
    }
    return s[:i+1]
}
1
2
3
4
5
6
7
function trimTrailingVowels(s: string): string {
    let i = s.length - 1;
    while (i >= 0 && 'aeiou'.indexOf(s[i]) !== -1) {
        i--;
    }
    return s.slice(0, i + 1);
}

Comments