力扣(LeetCode)试题3-无重复字符的最长子串 C++代码

感想:今天学到了新知识,unordered_set与unorder_map数据类型,可以提供查找(find)、移除(erase)与插入(insert)功能。

这个程序在报错→调试→报错→调试…中完成。

 1 #include <iostream>
 2 #include <string>
 3 #include <unordered_set>
 4 
 5 using namespace std;
 6 
 7 class Solution 
 8 {
 9 public:
10     int lengthOfLongestSubstring(string s) 
11     {
12         if (s.size() == 0) return 0;
13         unordered_set<char> str;//第一次学习这种容器,不能放入重复元素,提供了插入、删除、查询功能,容器名字叫lookup,容器内的元素类型为char
14         int lenth = 0;
15         int left = 0;
16 
17         for (int i = 0; i < s.size(); i++)//遍历输入的串
18         {
19             while (str.find(s[i]) != str.end())//如果找到了
20             {
21                 if (str.size() > lenth)
22                 {
23                     lenth = str.size();//先将当前的str长度给lenth,然后再操作str
24                 }
25                 str.erase(s[left]);    
26                 left += 1;            
27             }
28 
29             while (str.find(s[i]) == str.end())//如果在容器中找到了s[i]元素,fimd函数会返回一个迭代器;否则返回end()
30                 //如果没找到,则在容器中插入该元素
31             {
32                 str.insert(s[i]);
33             }
34         }
35         if (str.size() > lenth)
36             lenth = str.size();
37         return lenth;
38 
39     }
40 };
41 
42 
43 int main()
44 {
45     int result;
46     string s = "ab";
47     Solution sol;
48     result = sol.lengthOfLongestSubstring(s);
49     cout << result << endl;
50 
51     int u;
52     cin >> u;
53     return 0;
54 }

 

posted @ 2020-07-15 21:06  ZyLin-ux  阅读(185)  评论(0编辑  收藏  举报