Given a string S, remove the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ from it, and return the new string.
Example 1:
Input: “leetcodeisacommunityforcoders”
Output: “ltcdscmmntyfrcdrs”Example 2:
Input: “aeiou”
Output: “”S consists of lowercase English letters only.
1 <= S.length <= 1000
Loop and Remove
The usual approach will be looping the string and check each character. Ignore the vowels or otherwise push it to the result string.
class Solution {
public:
string removeVowels(string S) {
string s = "";
for (const auto &n: S) {
if (string("aeiou").find(n) == string::npos) {
s.push_back(n); // s += n;
}
}
return s;
}
};
Using Modern C++ std::accumulate()
With the std::accumulate() in Modern C++ e.g. C++14, we need to pass the begin and end iterators, the initial value which is set to a mutable string/vector, and a accmulator function.
class Solution {
public:
string removeVowels(string S) {
return std::accumulate(begin(S), end(S), std::string{}, [](auto &a, auto &b) {
if (string("aeiou").find(b) == string::npos) {
return a + b;
}
return a; // b is vowel, ignore
});
}
};
It is worth pointing out that the “” in C++ is interpreted to char* by default, that is why we need to explicitly cast it to string type before using the find() method.
See also: Teaching Kids Programming – Remove Vowels from a String
–EOF (The Ultimate Computing & Technology Blog) —
290 wordsLast Post: How to Compute the Min Cost of Climbing Stairs via Dynamic Programming Algorithm?
Next Post: Classic Unlimited Knapsack Problem Variant: Coin Change via Dynamic Programming and Depth First Search Algorithm