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;
    	}
    };
    
    
  • 相关阅读:
    css基本的东西
    css写一个梯形
    js事件代理
    css的垂直居中
    css的6中居中的方式
    css的小三角实现的方式
    css清楚浮动的几种常用方法
    css中的伪类和伪元素
    js回调
    11.10 chkconfig:管理开机服务
  • 原文地址:https://www.cnblogs.com/pk28/p/8587835.html
Copyright © 2011-2022 走看看