最长公共字符子串C++实现

本文提供了一个指向百度文库的链接,该链接用于查看一个具体的文档内容。通过这个链接可以访问到百度文库中的一篇文章。
http://wenku.baidu.com/view/907c1a18fc4ffe473368ab1a.html
使用 C++ 解决最长无重复字符子串问题可以采用滑动窗口的方法,以下是几种实现方案: ### 方案一:使用 `unordered_map` 记录字符位置 ```cpp #include <unordered_map> #include <algorithm> class Solution { public: int lengthOfLongestSubstring(std::string s) { int n = s.size(); std::unordered_map<char, int> mp; // 记录每个字符最近出现的位置 int left = 0, right = 0, ans = 0; // 窗口的左右边界和最长子串的长度 while (right < n) { if (mp.find(s[right]) == mp.end()) { // 如果当前字符没有出现过 mp[s[right]] = right; // 记录当前字符最近出现的位置 ans = std::max(ans, right - left + 1); // 更新最长子串的长度 right++; // 将右边界右移 } else { // 如果当前字符已经出现过 mp.erase(s[left]); // 将左边界左移 left++; // 将左边界左移 } } return ans; } }; ``` 该方案通过 `unordered_map` 记录每个字符最近出现的位置,使用滑动窗口不断更新最长无重复字符子串的长度。当遇到重复字符时,移动左边界直到窗口内无重复字符 [^1]。 ### 方案二:使用 `unordered_set` ```cpp #include <unordered_set> #include <algorithm> class Solution { public: int lengthOfLongestSubstring(std::string s) { // 哈希集合,记录每个字符是否出现过 std::unordered_set<char> occ; int n = s.size(); // 右指针,初始值为 -1,相当于在字符串的左边界的左侧,还没有开始移动 int rk = -1, ans = 0; // 枚举左指针的位置,初始值隐性地表示为 -1 for (int i = 0; i < n; ++i) { if (i != 0) { // 左指针向右移动一格,移除一个字符 occ.erase(s[i - 1]); } while (rk + 1 < n && !occ.count(s[rk + 1])) { // 不断地移动右指针 occ.insert(s[rk + 1]); ++rk; } // 第 i 到 rk 个字符是一个极长的无重复字符子串 ans = std::max(ans, rk - i + 1); } return ans; } }; ``` 此方案使用 `unordered_set` 来判断字符是否重复,通过枚举左指针,不断移动右指针,更新最长无重复字符子串的长度 [^3]。 ### 方案三:使用 `map` 实现滑动窗口 ```cpp #include <iostream> #include <map> #include <algorithm> int lengthOfLongestSubstring(std::string s) { int i = 0, j = 1, maxLen = 0; std::map<char, int> chars; if (s.size() > 0) { chars[s[0]] = 1; maxLen = 1; } while (i < s.length() && j < s.length()) { if (chars.find(s[j]) == chars.end()) { chars[s[j]] = 1; j++; } else { maxLen = std::max(maxLen, static_cast<int>(chars.size())); while (chars.find(s[j]) != chars.end()) { chars.erase(s[i]); i++; } } } maxLen = std::max(maxLen, static_cast<int>(chars.size())); return maxLen; } ``` 该方案利用 `map` 存储字符,当遇到重复字符时,移动左指针直到窗口内无重复字符,同时更新最长子串长度 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值