最长无重复字符的子串--动态规划

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

你可能感兴趣的:(算法,JAVA)