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)
  • 相关阅读:
    设计模式:生产者消费者模式
    图解SSH原理
    监听Google Player下载并获取包名等信息
    android targetSdkVersion>=26收不到广播的处理
    ant property file刷新不及时
    maven的pom文件报错: must be "pom" but is "jar"
    AJAX其实就是一个异步网络请求
    String、StringBuffer、StringBuilder的区别
    Properties、ResourceBundle
    JavaWeb--Listener
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4758466.html
Copyright © 2011-2022 走看看