第一个不重复的字符
循环超时
class Solution { public: int firstUniqChar(string s) { for(int i=0;i<s.size();i++) { bool ok=true; for(int j=0;j<s.size();j++) { if(j==i) continue; if(s[i]==s[j]) ok=false; } if(ok) return i; } return -1; } };
哈希表
class Solution { public: int firstUniqChar(string s) { unordered_map<int, int> position; int n = s.size(); for (int i = 0; i < n; ++i) { if (position.count(s[i])) { position[s[i]] = -1; } else { position[s[i]] = i; } } int first = n; for (auto [_, pos]: position) { if (pos != -1 && pos < first) { first = pos; } } if (first == n) { first = -1; } return first; } }; 作者:LeetCode-Solution 链接:https://leetcode.cn/problems/first-unique-character-in-a-string/solution/zi-fu-chuan-zhong-de-di-yi-ge-wei-yi-zi-x9rok/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】