[英]Why is iteration through a char vector is faster than the iteration through a string in C++
我正在練習編碼挑戰,我必須reverse the vowels in a string
。
My first approach failed because of exeeding Time limit.
這是我使用字符串迭代來反轉字符串中的元音的第一種方法。
string reverseVowels(string s) {
string str = "";
//storing the vowels from the string into another string
for (auto x : s)
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U')
str = str + x;
//swapping the vowels
int count = 0;
for (int i = s.size() - 1; i >= 0; i--)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')
{
s[i] = str[count];
count++;
}
}
return s;
}
My second approach using the char vector iteration had passed all the tests.
這是我的第二種方法
class Solution {
public:
string reverseVowels(string s) {
vector<char> v;
//storing the vowels from the string into vector
for (auto x : s)
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U')
v.push_back(x);
//swapping the vowels
int count = 0;
for (int i = s.size() - 1; i >= 0; i--)
{
if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')
{
s[i] = v[count];
count++;
}
}
return s;
}
};
你能解釋一下為什么我的第一種方法沒有通過測試,而第二種方法通過了測試
替換str = str + x;
與str.push_back(x);
或str += x;
,您可能會看到與vector
相同的性能。
str = str + x;
制作str
的副本,將字符附加到該副本,然后在分配回str
時制作另一個副本。 結果,您的算法是二次的,沒有充分的理由。
這是因為您正在執行str = str + x
,這會創建str
的不必要副本,但是std::vector::push_back
或std::string::push_back
將字符附加到向量或字符串,這比創建str
的副本。
str = str + x
這會在復制時創建一個額外的 str 副本。 std::vector::push_back
這個直接附加到向量字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.