zoukankan      html  css  js  c++  java
  • [leedcode 03] 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.

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            //利用hashMap只需循环一次即可。
             //使用start和i两个指针维护子串,用Hash表记录字串中出现的字符。每次循环i右移1位,然后判断i右移之后所指向的字符是否在Hash表中出现            过:如果出现过,则表示出现重复字符,记录该子串长度,并与最长长度比较,然后,删除子串中重复字母之前的字符,并更新start;如果没出现过,         则说明没有重复字符,将该字符放入Hash表。
             /*
             时间复杂度O(n);
             空间复杂度O(m),m取决于非重复子串的长度*/
            HashMap<Character,Integer> map=new HashMap<Character,Integer>();
            int len=0;
            int res=0;
        
            int start=0;
            int i=0;
            for(i=0;i<s.length();i++){
                if(!map.containsKey(s.charAt(i))){
                    map.put(s.charAt(i),i);
                   /*  len=i-start+1;
                     res=Math.max(len,res);*/
                }else{
                     len=i-start;
                     res=Math.max(len,res);
                    int t=map.get(s.charAt(i));
                    for(int j=start;j<=t;j++){
                        map.remove(s.charAt(j));
                    }
                    start=t+1;
                    map.put(s.charAt(i),i);
                }
            }
            return Math.max(res,i-start);
           // return res;
        }
    }
  • 相关阅读:
    .Net Remoting浅释
    初级SQL开发汇总指南
    WPF Navigation导航
    WPF Button的背景图片设置
    2015/9/20 Python基础(16):类和实例
    2015/9/19 Python基础(15):变量作用域及生成器
    2015/9/18 Python基础(14):函数式编程
    2015/9/17 Python基础(13):函数
    2015/9/15 Python基础(12):模块和包
    2015/9/10 Python基础(11):错误和异常
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4620601.html
Copyright © 2011-2022 走看看