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)
  • 相关阅读:
    游遍中国 —— 大街小巷、秘境与远方
    Batch Normalization 反向传播(backpropagation )公式的推导
    Batch Normalization 反向传播(backpropagation )公式的推导
    【社会/人文】概念的理解 —— 断舍离、饭(饭制版)
    【社会/人文】概念的理解 —— 断舍离、饭(饭制版)
    linux 线程的同步 一 (互斥量和信号量)
    linux find
    正则表达式30分钟入门教程-新
    linux sed命令详解 *****
    linux vim tutor
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4758466.html
Copyright © 2011-2022 走看看