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;
    	}
    };
    
    
  • 相关阅读:
    hdoj 2544 最短路径
    树状数组 hdoj1166
    并查集学习
    1402大数相乘 FFT算法学习!
    hdu1014
    动态规划 简单题dp
    迷宫路径
    简单的动态规划dp
    poj 3282 (bFS)
    背包问题,看不懂,啊!!!!!!!!dp
  • 原文地址:https://www.cnblogs.com/pk28/p/8587835.html
Copyright © 2011-2022 走看看