C++判断字符串字符是否重复的repeats函数如何优化精简?
C++判断字符串重复字符函数优化方案
你的原有代码采用双重循环实现,时间复杂度为O(n²),且遍历完全部字符才返回,存在较大的优化空间,同时可以借助C++标准库能力大幅减少代码行数。
方案1:最简实现(仅3行核心逻辑,适合短字符串场景)
借助排序和相邻查找算法,代码最精简:
#include <algorithm> #include <string> bool repeats(const std::string& s) { std::string sorted_s = s; std::sort(sorted_s.begin(), sorted_s.end()); return std::adjacent_find(sorted_s.begin(), sorted_s.end()) != sorted_s.end(); }
- 逻辑说明:排序后重复字符会自动相邻,
std::adjacent_find会直接查找第一个相邻相等的字符,找到即代表存在重复,直接返回true。
方案2:*O(n)*时间复杂度实现(适合长字符串场景)
借助哈希集合实现线性时间复杂度,性能更优:
#include <unordered_set> #include <string> bool repeats(const std::string& s) { std::unordered_set<char> char_set; for (char c : s) if (!char_set.insert(c).second) return true; return false; }
- 逻辑说明:遍历字符时尝试插入哈希集合,插入失败则说明该字符已经出现过,直接返回存在重复,无需遍历剩余字符。
内容的提问来源于stack exchange,提问作者xcell
相关产品推荐
相关产品推荐

