LeetCode第3题--无重复字符串的最长子串

题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/

package com.leetcode.leetcode_003;

//import javax.management.relation.RoleUnresolvedList;

import java.util.HashMap;import java.util.Map;public class Soluton {
    /*给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
    示例 1:
    输入: "abcabcbb"
    输出: 3
    解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
    示例 2:
    输入: "bbbbb"
    输出: 1
    解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
    示例 3:
    输入: "pwwkew"
    输出: 3
    解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
    p w w k e w
    j   i   res = i-j = 2 - 0 = 2; j = map.get(i) + 1;//j = 2;

    j = 0; ===>
                 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
    public static void main(String[] args) {
        Soluton so = new Soluton();
        String s = "pwwkewfdsfsfsafa";//最大字串长度6
        String spStr = "bbbbb";
//        System.out.println("length = " + spStr.length());
//        System.out.println(so.lengthOfLongestSubString(s));
//        System.out.println(so.lengthOfLongestSubString(spStr));
        System.out.println(so.lengthOfLongestSubStringHashMap(s));
    }

    public int lengthOfLongestSubStringHashMap(String s) {
        if (s == null || s.length() == 0) return 0;
        int res = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0, j = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
//                res = Math.max(i - j + 1, res);
//                j = map.get(s.charAt(i)) + 1;//此写法忽略了含有多个重复的情况
                j = Math.max(j, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            res = Math.max(i - j + 1, res);
        }
        return res;
    }

 据说还可以用HashSet做,希望会做的发下代码!



猜你喜欢

转载自www.cnblogs.com/BearBird/p/12013477.html