博客 / 詳情

返回

JZ-073-最長不含重複字符的子字符串

最長不含重複字符的子字符串

題目描述

輸入一個字符串(只包含 a~z 的字符),求其最長不含重複字符的子字符串的長度。例如對於 arabcacfr,最長不含重複字符的子字符串為 acfr,長度為 4。

題目鏈接: [最長不含重複字符的子字符串]()

代碼

import java.util.Arrays;

/**
 * 標題:最長不含重複字符的子字符串
 * 題目描述
 * 輸入一個字符串(只包含 a~z 的字符),求其最長不含重複字符的子字符串的長度。例如對於 arabcacfr,最長不含重複字符的子字符串為 acfr,長度為 4。
 */
public class Jz73 {

    public 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;
    }

    public static void main(String[] args) {
        
    }
}
【每日寄語】 為人子,方少時;親師友,習禮儀。
user avatar xiaoxiaofeng_java 頭像 seazhan 頭像 fu_623f04ad34d53 頭像 dolphinscheduler 頭像 mackyhuang 頭像
5 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.