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;
        }
    }
    

      

  • 相关阅读:
    file_put_contents 和php://input 实现存储数据进图片中
    Oracle PL/SQL游标的学习
    三层的再理解
    取出字符串中任意的顺序匹配
    oracle的正则表达式(regular expression)简单介绍
    oracle动态游标的简单实现方法
    存储过程之游标笔记小结
    char,varchar,nvarchar的区别
    大连惊魂记
    让asp.net默认的上传组件支持进度条反映(转)
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/6129826.html
Copyright © 2011-2022 走看看