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

      

  • 相关阅读:
    巴洛克式和哥特式的区别
    推荐阅读书籍,是时候再行动起来了。
    AtCoder ABC 159F Knapsack for All Segments
    AtCoder ABC 159E Dividing Chocolate
    AtCoder ABC 158F Removing Robots
    AtCoder ABC 158E Divisible Substring
    AtCoder ABC 157F Yakiniku Optimization Problem
    AtCoder ABC 157E Simple String Queries
    AtCoder ABC 157D Friend Suggestions
    AtCoder ABC 156F Modularness
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/6129826.html
Copyright © 2011-2022 走看看