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;
    	}
    };
    
    
  • 相关阅读:
    透视投影矩阵的推导
    选择排序
    递归运动函数的实现
    插入排序
    基本光照模型
    顶点法向量从物体坐标系变换到世界坐标系
    Phong和BlinnPhong光照模型
    unity3d使用脚本保存屏幕截图
    【转】C++11常用特性的使用经验总结
    右手坐标系下LookAt视图矩阵的推导
  • 原文地址:https://www.cnblogs.com/pk28/p/8587835.html
Copyright © 2011-2022 走看看