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)
  • 相关阅读:
    day17 内置方法、数学模块、randrange随机模块、序列化模块pickle
    线性模型L2正则化——岭回归
    KMP算法
    KNN算法:KNN-classifier和KNN-regressor
    机器学习开篇——编译器的选择
    STL好坑
    树状数组学习笔记
    无题
    最小树形图:朱刘算法
    2019ICPC徐州站题解
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4758466.html
Copyright © 2011-2022 走看看