Title

给定一个字符串, 输出其中没有重复值的, 最长子串的长度

给定一个字符串, 输出其中没有重复值的, 最长子串的长度

 

样例输入:

abcabcabc

样例输出:

3

 

样例输入:

pwwkew

样例输出:

3

package com.work2021;

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

/**
 * @ClassName: Assignment_31
 * @Description: one new test
 * @author: Yu wang
 * @date: Created in 2021/3/6  8:38
 */
public class Assignment_31 {
    static public Scanner sc = new Scanner(System.in);
    static public color color = new color();
    public static void main(String[] args) {
        do {
            new Assignment_31().work();
            System.out.println(color.color1() + "\n继续输入0,退出输入1");   //循环判断
        } while (sc.nextInt() != 1);
    }
    public void work(){
        System.out.println(color.color1()+"输入一串字符:");
        String s = sc.next();
        int a = lengthOfLongestSubstring(s);
        System.out.println(color.color1()+"第一种方法最长子串的长度"+color.color2()+a);
        int b = lengthOfLongestSubstring_2(s);
        System.out.println(color.color1()+"第二种方法最长子串的长度"+color.color2()+b);
    }
    //第一种
    public static int lengthOfLongestSubstring(String s){
        int fs = 0;//用于存取最后要返回的长度
        //1.创建一个map,key:字符,value: 字符下标  `
        Map<Character,Integer> map = new HashMap<>();
        //2.遍历字符串,并将字符串存入map中
        for (int start = 0,end = 0; end < s.length(); end++) {
            char ch = s.charAt(end);
            if (map.containsKey(ch)){ //若已经存在于map中,则将其对应的value拿出来
                start = Math.max(map.get(ch),start);
            }
            // 取较大值
            fs = Math.max(fs,end - start +1);
            //存入map中
            map.put(ch,end + 1);
        }
        return fs;
    }
    //第二种
    public static int lengthOfLongestSubstring_2(String s ){
        int fa = 0;
        int n = s.length();
        int [] map = new int[128];
        char [] ch = s.toCharArray();
        for (int j = 0, i = 0; j < n; j++) {
            //取较大值并赋值给 i,找到对应map数组下标对应的值,和 i 值比较
            i = Math.max(map[ch[j]],i);
            //字符串的长度等于最后一个字符的下标 - 最前面一个字符的下标
            fa = Math.max(fa,j-i+1);
            map[ch[j]] = j + 1; //以字符作为map数组的下标,并给对应的下标赋值
        }
        return fa;
    }
}

 

posted @ 2021-03-06 10:35  WAASSTT  阅读(279)  评论(0)    收藏  举报
Title