C++ 反转字符串中的单词:优化超时问题
这段代码可能会超时,因为它使用了两个嵌套的 while 循环,其中一个循环用于找到每个单词的起点和终点,另一个循环用于将每个单词添加到结果字符串中。这样做的时间复杂度是 O(n^2),其中 n 是字符串的长度。
为了避免超时,可以使用一个双端队列来存储每个单词,然后将队列中的单词按照逆序添加到结果字符串中。这样做的时间复杂度是 O(n),其中 n 是字符串的长度。以下是修改后的代码:
class Solution {
public:
string reverseWords(string s) {
deque<string> words;
string word;
for (char c : s) {
if (c == ' ') {
if (!word.empty()) {
words.push_front(word);
word.clear();
}
} else {
word += c;
}
}
if (!word.empty()) {
words.push_front(word);
}
string ans;
for (string& w : words) {
ans += w;
ans += ' ';
}
if (!ans.empty()) {
ans.pop_back();
}
return ans;
}
};
这段代码使用一个双端队列来存储每个单词,然后将队列中的单词按照逆序添加到结果字符串中。这样做的时间复杂度是 O(n),其中 n 是字符串的长度。
原文地址: https://www.cveoy.top/t/topic/opNN 著作权归作者所有。请勿转载和采集!