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)
  • 相关阅读:
    让flask在出现语法错误时仍然自动重启
    ubuntu配置zsh和oh-my-zsh
    docker运行python3.6+flask小记
    vscode python3 配置生成任务
    从flask视角理解angular(四)Route
    从flask视角理解angular(三)ORM VS Service
    从flask视角理解angular(二)Blueprint VS Component
    从flask视角学习angular(一)整体对比
    Linux高级变量
    linux系统中查看日志及系统信息
  • 原文地址:https://www.cnblogs.com/theskulls/p/4758466.html
Copyright © 2011-2022 走看看