c++中string拼接效率
+和 +=的差别: + 相比于 += 执行过程中会多产生一个新对象。
str = str + a;
该语句先将等号右边的两个string对象内容相加,得到一个新的string对象。再把这个新的对象赋给等号左边的string对象。
str += a;
该语句直接将等号右边的string对象内容追加到左边的string对象后面。
leetcode1047:删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> _stack;
string result;
for(int i = 0;i < s.size();i++)
{
if(!_stack.empty() && s[i] == _stack.top())
{
_stack.pop();
}else{
_stack.push(s[i]);
}
}
while(!_stack.empty())
{
result = _stack.top() + result;//头插法(超时的罪魁祸首)
_stack.pop();
}
return result;
}
};
使用赋值语句使结果超时,无法通过。
class Solution {
public:
string removeDuplicates(string s) {
stack<char> _stack;
string result;
for(int i = 0;i < s.size();i++)
{
if(!_stack.empty() && s[i] == _stack.top())
{
_stack.pop();
}else{
_stack.push(s[i]);
}
}
while(!_stack.empty())
{
result += _stack.top();//尾插
_stack.pop();
}
reverse (result.begin(), result.end()); // 字符串反转
return result;
}
};
成功通过