What is the complexity of my vowel_remove in string? Is there any faster way?
This is a simple code that removes vowel. What is the complexity of my code (Big-O) and is there a better way to do it? Thanks
int main()
{
// char *text;
// text = new char[];
string a = "remove vowels";
string b = a;
int index = 0;
for (int i = 0; i < a.length(); i++)
{
cout << a[i] << endl;
if (a[i] != 'a' && a[i] != 'e' && a[i] != 'i' && a[i] != 'o' && a[i] != 'u')
{
b[index] = a[i];
index++;
}
}
b.resize(index);
cout << b << endl;;
// delete[] text;
system("pause");
return 0;
}
What is the complexity of my code (Big-O) |
Linear: O(n)
there a better way to do it? |
Use standard library:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
//Variant 1 Modifying original string
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string a = "remove vowels";
auto is_vowel = [](char c){return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';};
a.erase(std::remove_if(a.begin(), a.end(), is_vowel), a.end());
std::cout << a;
}
//Variant 2 Copying results to new string
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string a = "remove vowels";
auto is_not_vowel = [](char c)
{return c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u';};
std::string b;
std::copy_if(a.begin(), a.end(), std::back_inserter(b), is_not_vowel);
std::cout << b;
}
|
Topic archived. No new replies allowed.