欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

一道vector实现字典的题目 C++

发布时间:2025/6/17 c/c++ 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 一道vector实现字典的题目 C++ 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

使用vector 在解决一些问题的时候确实非常高效。
可以不像Array 那样一个一个去查。
可以大幅度缩减代码实现的时间。
Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

https://leetcode.com/problems/longest-substring-without-repeating-characters/submissions/
Leetcode 里面的第三题我的解法,非常冗长。

int main(){string s = "qrebtmppwuuhapcegnaon";char t_string[101]="";int max_ceil = 0;int ceil = 0;for (int i=0; i<s.length()-max_ceil;i++){for(int j=0; j<s.length()-i; j++){for(int k=0; k < ceil;k++){if(s[i+j] == t_string[k]){if(ceil>max_ceil){max_ceil = ceil;}ceil=0;j=0;i++;break;}}t_string[ceil]=s[i+j];ceil++;}}if(ceil>max_ceil){max_ceil = ceil;}cout<< max_ceil; return 0; }

在上面看到一个大神的解法,拿来分享。

int main(){string s="uvuioinmk";int maxLen = 0;vector<int> dict(256, -1);int start = -1;for(int i=0; i<s.length();i++){if(dict[s[i]]>start)//该重复字符有效...start = dict[s[i]]; //替换到最近出现的重复字符位置dict[s[i]] = i; //最近出现的位置maxLen = max(maxLen, i - start);}cout<<maxLen; }

注释是我自己加的,理解这个算法确实需要一点抽象思维。

转载于:https://www.cnblogs.com/venusian/p/10480872.html

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的一道vector实现字典的题目 C++的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。