剑指笔记——48 最长不含重复字符的子字符串

题目:最长不含重复字符的子字符串
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。例如,在字符串中”arabcacfr”,最长非重复子字符串为”acfr”,长度为4。

思路:这个很奇怪,这个题和leetcode中的第三题好像是一样的,但是把这个代码放在leetcode中总是报错。。。。先把剑指的思路放在这里:整体上使用动态规划来解题。首先定义函数f(i)表示以第i个字符为结尾的不包含重复字符的子字符串的最长长度。如果第i个字符之前没有出现过,那么f(i)=f(i-1)+1;如果之前出现过,我们先计算第i个字符和上次它出现的位置的距离d,分为两种情况:(1)如果d小于或者等于f(i-1),则f(i)=d;

   (2)如果d>f(i-1),依然有f(i)=f(i-1)+1

我们使用长度为26的数组存储每个字符上次出现在字符串中位置的下标。所有元素都初始化为1,表示该元素对应的字符在字符串中没有出现过。

下面还有leetcode中的代码,还是看不懂。。。。这部分代码好像是维护一滑动窗口。j表示的是窗口的右边界,i表示的是窗口的左边界。数组index记录的是对应的字符串上一次出现的位置,如果该字符串还没有出现过,就是默认值0.当遍历数组时,找到j出的元素之前出现的位置,将其与左边界i比较,如果比左边界小,则i的值不变;如果比左边界i大,则更新i的值。

其实以上两种思路相差不是特别大,leetcode中更为简洁。

代码:

public class LongestSingleSubstring
{
    private static int findLongestSubstringLength(String string)
    {
        if (string == null || string.equals("")) return 0;
        int maxLength = 0;
        int curLength = 0;
        int[] positions = new int[26];
        for (int i = 0; i < positions.length; i++)
        {
            positions[i] = -1; //初始化为-1,负数表示没出现过
        }
        for (int i = 0; i < string.length(); i++)
        {
            int curChar = string.charAt(i) - 'a';
            int prePosition = positions[curChar];
            //当前字符与它上次出现位置之间的距离
            int distance = i - prePosition;
            //当前字符第一次出现,或者前一个非重复子字符串中没有包含当前字符
            if (prePosition < 0 || distance > curLength)
            {
                curLength++;
            } else
            {
                //更新最长非重复子字符串的长度
                if (curLength > maxLength)
                {
                    maxLength = curLength;
                }
                curLength = distance;
            }
            positions[curChar] = i; //更新字符出现的位置
        }
        if (curLength > maxLength)
        {
            maxLength = curLength;
        }
        return maxLength;
    }
}

leetcode 代码:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/chenxy132/article/details/89467503
今日推荐