最長無重複字符的子串--動態規劃

Longest Substring Without Repeating Characters:

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

尋找最長無重複字符的子串

注:子串是完全相鄰的字符集合,而子序列是從左向右順序的不一定相鄰的字符集合,注意其區別

給定一個字符串,尋找其最長無重複字符的子串的長度
例如
“abcabcbb” –> “abc”, length = 3
“bbbbb” –> “b”, length = 1
“pwwkew” –> “wke”, length 3

public class Solution {
    public int lengthOfLongestSubstring(String s) {

        if (s==null || s.length() == 0) return 0;

        //記錄字符上一次出現的位置,ascii字符最多256個,所以長度爲256
        int[] lastPosOfChar = new int[256];
        //將上次此字符出現的位置初始化爲-1,代表未出現過
        Arrays.fill(lastPosOfChar, -1);
        int maxLength = 0;    // 最長子串長度
        int startPos = 0;     // 最長子串起始位置

        //採用動態規劃算法,將目標字符串遍歷一遍,即可得出結果
        for (int i = 0; i < s.length(); i++) {
            //如果當前字符未出現過或者字符上次出現的位置小於startPos,
            //則子串起始位置依然是startPos;
            //否則startPos便是上次出現此字符的位置+1
            startPos = (startPos > lastPosOfChar[s.charAt(i)])? startPos : (lastPosOfChar[s.charAt(i)] + 1);
            //字符遍歷過後,便記錄其位置,
            //作爲後面的相同字符出現時更新子串起始位置的憑據
            lastPosOfChar[s.charAt(i)] = i;
            //遍歷過當前字符後,當前子串的無重複長度便爲:i - startPos + 1
            //然後和過往的子串長度maxLength比較,保留最大值
            maxLength = (i - startPos + 1 > maxLength)? (i - startPos + 1) : maxLength;

        }

        return maxLength;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章