[Leetcode] 3.Longest Substring Without Repeating Characters(unordered_map)

通过把未访问的结点放到unordered_map中来判断是否重复,代码如下:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         if(s == "")
 5             return 0;
 6         unordered_map<char,int> hash;
 7         int len = 0;
 8         int res = 0;
 9         for(int i = 0;i < s.length();i ++)
10         {
11             if(hash.find(s[i]) != hash.end())
12             {
13                 i = hash[s[i]];
14                 hash.clear();
15                 len = 0;
16             }
17             else
18             {
19                 hash[s[i]] = i;
20                 len ++;
21                 res = max(len, res);
22             }
23         }
24         return res;
25     }
26 };

 

posted @ 2017-01-31 18:24  Strawberry丶  阅读(176)  评论(0编辑  收藏  举报