美文网首页
剑指 offer 学习之最长不含重复字符的子字符串

剑指 offer 学习之最长不含重复字符的子字符串

作者: Kevin_小飞象 | 来源:发表于2020-03-26 09:07 被阅读0次

    题目描述

    输入一个字符串(只包含 a~z 的字符),求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。

    解题思路

    import java.util.*;
    public class Main {
        
        public static void main(String[] args) {
            
            System.out.println(longestSubStringWithoutDuplication("arabcacfr"));
        }
        
        public static int longestSubStringWithoutDuplication(String str) {
            int curLen = 0;
            int maxLen = 0;
            int[] preIndexs = new int[26];
            Arrays.fill(preIndexs, -1);
            for (int curI = 0; curI < str.length(); curI++) {
                int c = str.charAt(curI) - 'a';
                int preI = preIndexs[c];
                if (preI == -1 || curI - preI > curLen) {
                    curLen++;
                } else {
                    maxLen = Math.max(maxLen, curLen);
                    curLen = curI - preI;
                }
                preIndexs[c] = curI;
            }
            maxLen = Math.max(maxLen, curLen);
            return maxLen;
        }
    }
    
    

    测试结果

    image.png

    相关文章

      网友评论

          本文标题:剑指 offer 学习之最长不含重复字符的子字符串

          本文链接:https://www.haomeiwen.com/subject/autxuhtx.html