查找出一個字符串不重複字符的最大長度

package com.xiaobu.leetcode;

import com.xiaobu.base.util.StringUtil;

import java.util.HashMap;

/**
 * @author xiaobu
 * @version JDK1.8.0_171
 * @date on  2020/3/27 14:38
 * @description 查找出一個字符串不重複字符的最大長度
 * https://segmentfault.com/a/1190000016216003
 */
public class TheMaxLengthOfNotRepeate {
    public static int getTheMaxLengthOfNotRepeate(String str) {
        if (StringUtil.isNullOrEmpty(str)) {
            return 0;
        }
        HashMap<Character, Integer> map = new HashMap<>();
        //出現的位置
        int max = 0;
        //重複的位置
        int pre = -1;
        for (int i = 0, strLen = str.length(); i < strLen; i++) {
            Character ch = str.charAt(i);
            Integer index = map.get(ch);
            if (index != null) {
                pre = Math.max(index, pre);
            }
            max = Math.max(max, i - pre);
            map.put(ch, i);
        }
        return max;
    }


    public static void main(String[] args) {
        String str = "abcdefg";
        System.out.println(getTheMaxLengthOfNotRepeate(str));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章