最长不重复子串

问题描述

给定一个字符串,找到最长的子串,要求该子串中没有重复的字符。
例如:
字符串abcabcbb的不含重复字符的最长子串为abc,长度为3。
bbbbbb的不含重复字符的最长子串为b,长度为1。

输入格式

输入包含多行,每一行对应一个长度不超过100 的输出,直到遇到结束符为止。每行依次输入字符串s

输出格式

输出不含重复字符的最长子串的长度。

代码

package javaexam;

import java.util.HashMap;
import java.util.Scanner;

/**
 * @author houhaibushihai
 * The longest non repeating substring
 *
 */
public class LongestNRS
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        
        while(input.hasNext())
        {
            int max = 0;
            int start = 0;
            HashMap<Character, Integer> map = new HashMap<Character, Integer>();
            String str = input.nextLine();
            
            for(int i = 0; i < str.length(); ++i)
            {
                if(map.containsKey(str.charAt(i)))
                    start = Math.max(start, map.get(str.charAt(i)) + 1);
                
                map.put(str.charAt(i), i);
                max = Math.max(max, i - start + 1);
            }
            System.out.println(max);
        }
    }
}

样例测试

hchzvfrkmlnozjk
11

猜你喜欢

转载自www.cnblogs.com/narisu/p/9057909.html