zoukankan      html  css  js  c++  java
  • leetcode 3. Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Examples:
    
    Given "abcabcbb", the answer is "abc", which the length is 3.
    
    Given "bbbbb", the answer is "b", with the length of 1.
    
    Given "pwwkew", 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.
    

    思路:用map维护区间内各个字母的数量,然后遇到已经访问过的就进行滑动区间,来得到符合条件的区间,然后求最大区间长度。

    class Solution {
    	public:
    	int lengthOfLongestSubstring(string s) {
    		int ans = 0;
    		int l = 0;
    		unordered_map<char, int> mp;
    		for (int i = 0; i < s.size(); ++i) {
    			if (!mp[s[i]]) ++mp[s[i]];
    			else {
    				while (l < i && mp[s[i]] > 0) {
    					--mp[s[l]];
    					++l;
    				}
    				mp[s[i]] = 1;
    			}
    			ans = max(ans, i - l + 1);
    		}
    		return ans;		
    	}
    };
    
    

    虽然时间复杂度是O(n)但是感觉比最好的代码还是慢了点。

    这个代码可以改进一下,首先不用 unordered_map做为映射结构,用vector<int>v(256) 256是ASII表的大小。字母表先初始话为-1,然后用l表示s[i]上一次出现的位置,具体实现见代码。

    class Solution {
    	public:
    	int lengthOfLongestSubstring(string s) {
    		if (s.empty()) return 0;
    		int ans = 0;
    		vector<int> v(256, -1);
    		int l = -1;
    		for (int i = 0; i < s.size(); ++i) {
    			if (v[s[i]] > l) l = v[s[i]];
    			v[s[i]] = i;
    			ans = max(ans, v[s[i]] - l);
    		}
    		return ans;
    	}
    };
    
    
  • 相关阅读:
    vbscript 语言通过序列和ADODB实现取号不重复
    arcgisserver成功发布服务后,浏览服务,无地图显示
    GUID的获取
    EasyUi 表格自适应宽度
    接口隔离原则
    依赖倒置原则
    开放封闭原则
    单一职责原则
    python-函数基础
    python -流程控制
  • 原文地址:https://www.cnblogs.com/pk28/p/8587835.html
Copyright © 2011-2022 走看看