zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    我的思路:

    首先是设置了start和i两个变量,其中start用于指示当前子串首的前一个字符的位置,i表示当前子串尾字符的位置。数组posflag用于记录出现过的重复字符的当前最新位置(忽略当前字符,也就是当前字符上次出现的位置)。主要分支有两部分,第一部分是当前字符非重复字符,此时应该将该字符放入posflag以更新,另外需要记录此时合法子串的长度是否比记录的最长子串长,并进行更新操作;第二部分是出现重复字符时的处理,此时应该将start的位置移至重复字符上次出现的位置(但是需要注意的是:start只能向后移动,不能向前移动,这个易证,所以在这里会有斜线部分的判断语句),然后更新字符出现位置,并且比较当前子串长度是否大于记录的最大子串长以便做相应的更新。代码如下

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
        	int[] posflag = new int[256];
        	for(int i = 0;i < 256; i++)
        		posflag[i] = -1;
        	int start = -1,max = 0;
        	for(int i = 0;i < s.length(); i++){
        		//System.out.println((int)s.charAt(i));    		
        		if(posflag[(int)s.charAt(i)]!=-1){
        			if(posflag[(int)s.charAt(i)]>start)
        				start = posflag[(int)s.charAt(i)];
        			posflag[(int)s.charAt(i)] = i;
        			if(i-start>max)
        				max = i-start;
        		}else{
        			
        			posflag[(int)s.charAt(i)] = i;
        			if(i-start>max)
        				max = i-start;
        		}
        	}
        	//System.out.println(max);
        	return max;
        }
    }
    

      

  • 相关阅读:
    vim黏贴代码格式混乱的解决方法
    fopen()和fclose()的用法
    简谈switch case
    【转】如何确定Kafka的分区数、key和consumer线程数
    【转】Kafka producer原理 (Scala版同步producer)
    【转】 使用maven创建web项目
    【转】使用Eclipse构建Maven项目 (step-by-step)
    eclipse的安装环境及eclipse下maven的配置安装
    strtol,strtoll,strtoul, strtoull字符串转化成数字
    Kafka Producer相关代码分析【转】
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/6129826.html
Copyright © 2011-2022 走看看