zoukankan      html  css  js  c++  java
  • 003 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.

    详见:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

    Java实现:

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] hash=new int[256];
            for(int i=0;i<256;++i){
                hash[i]=-1;
            }
            int maxLen=0;
            int start=-1;
            for(int i=0;i<s.length();++i){
                if(hash[s.charAt(i)]>start){
                    start=hash[s.charAt(i)];
                }
                hash[s.charAt(i)]=i;
                maxLen=Math.max(maxLen,i-start);
            }
            return maxLen;
        }
    }
    

    python实现:

    方法一:

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            start,ans,d=0,0,{}
            for i in range(len(s)):
                c=s[i]
                if c in d and d[c]>=start:
                    start=d[c]+1
                else:
                    ans=max(ans,i-start+1)
                d[c]=i
            
            return ans
    

     方法二:

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            ans, l, check = 0, 0, set()    
            for i in range(len(s)):
                if s[i] in check:
                    while l<i and s[i] in check:
                        check.discard(s[l])
                        l+=1
                check.add(s[i])
                ans=max(ans,len(check))
            
            return ans
    
  • 相关阅读:
    js 判断window操作系统 2种方法
    HTML5 16进制颜色
    html5 动画运动 属性
    html5 动画运动 属性
    html5 图片旋转 --位置定位
    html 5 过渡 属性 高度 宽度 颜色 样式等。。。
    jquery 文档操作
    html5 表单 自带验证
    PHP微信授权登录信息
    接口测试-requests高级用法
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8681587.html
Copyright © 2011-2022 走看看