zoukankan      html  css  js  c++  java
  • LeetCode 3-Longest Substring Without Repeating Characters

    Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    找出字符串中最长的不相同子串

    空 长度为0直接返回0

    长度为1,返回1

    对于大于1的情况

    遍历字符串:

    定义一个HashSet集合

    对字符串中的每个元素,若不存在集合中则,加入集合

    若已经存在集合中:假设这个元素是ch,要把加入集合ch之前的元素全部剔除,left加一

    while(s.charAt(left)!=ch){
                        set.remove(s.charAt(left));
                        left++;
                    }//end while
                    left++;

    上面就是主要的程序

    全部程序

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            HashSet set = new HashSet();
            int left = 0;
            int right = 0;
            int max = 0;
            char ch;
            if(s==null && s.length()==0) return 0;
            if(s.length()==1) return 1;
            for( right=0;right<s.length();right++){
                ch = s.charAt(right);
                if(set.contains(ch)){
                    max =Math.max(max,right-left);
                    
                    while(s.charAt(left)!=ch){
                        set.remove(s.charAt(left));
                        left++;
                    }//end while
                    left++;
                }else{
                    set.add(ch);
                    // right
                }//end if
            }//end for
             max = Math.max(max,right-left);
            return max;
        }//end 
    }

    Python 程序,没看懂

    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            if len(s)==0: return 0
            if len(s)==1: return 1
            lastAppPos={s[0]:0} #last appear position of alphabet 
            longestEndingHere=[1]*len(s) # longest substring ending here 
            for index in xrange(1,len(s)):
                lastPos = lastAppPos.get(s[index],-1)
                if lastPos<index-longestEndingHere[index-1]:
                    longestEndingHere[index] = longestEndingHere[index-1] + 1
                else:
                    longestEndingHere[index] = index - lastPos
                lastAppPos[s[index]] = index
            return max(longestEndingHere)
  • 相关阅读:
    微信支付-我遇到的那些问题
    [工作笔记]JDK版本不同导致的SSL异常
    mysql与oracle在groupby语句上的细节差异
    微信js-sdk调用
    循序渐进看Java web日志跟踪(3)-Log4J的使用和配置
    循序渐进看Java web日志跟踪(2)-Java日志API认识
    循序渐进看Java web日志跟踪(1)-Tomcat 日志追踪与配置
    手机号码正则表达式(含虚拟运营商)
    网站URL重写(Java UrlRewrite 的使用)
    TCP/IP提供网络传输速率
  • 原文地址:https://www.cnblogs.com/theskulls/p/4758466.html
Copyright © 2011-2022 走看看