题目大意是传入一条字符串,计算出这样的这样一条子字符串,要求子字符串是原字符串的连续的某一段,且子字符串内不包含两个或两个以上的重复字符。求符合上面条件的字符串中最长的那一条的长度。


首先注意到任意一条无重复子字符串的任意子字符串应该也满足无重复这一特性。因此这个问题可以用动态规划解决。

需要先计算出字符串s的每个元素对应的首个重复字符的下标,字符串中下标为i的元素的首个重复字符的下标j应该满足j > i && s[i] == s[j],且是满足这些条件中的最小值。比如asaa中下标为0的元素对应的首个重复字符的下标为2,尽管3也满足条件,但不是最小值。

计算的方式如下:

registries = int[256]

nextOccurance = int[s.length]

initialize elements in registries with -1 //将所有registries 中的元素都初始化为-1

initialize elements in nextOccurance with s.length //将所有registries 中的元素都初始化为s.length

for(i = 0; i < s.length; i++)

  c = s[i]

  if registries[c] != -1 then

    nextOccurance [registries[c]] = i

  registries[c] = i

这里用注册表registries的注册项registries[c]记录当前对字符c的查找请求,而nextOccurance的元素nextOccurance[i]表示s[i]的首个重复字符子s中的下标。每次循环时,都会检测注册表项registries[c]是否以及被注册,如果注册则为nextOccurance [registries[c]]记录当前下标i。最后则将之前的注册项清除,而用当前下标作为新的请求项。

之后使用动态规划解决问题。利用数组longestLengthes,longestLengthes[i]表示所有以下标i作为起始的无重复子字符串的最长长度。显然longestLengthes[s.length - 1]应该为1。而对于任意i < s.length - 1,应该有longestLengthes[i] = min(longestLengthes[i + 1] + 1, nextOccurance [i] - i)。其中longestLengthes[i + 1] + 1表示理想状态下(不考虑出现多个longestLengthes[i]对应的字符)的最优长度,而nextOccurance [i] - i表示可能的以下标i作为起始的无重复子字符串的最长长度,因为s[i] == s[nextOccurance [i]],这里已经发生了重复。之所以敢保证longestLengthes[i] <= longestLengthes[i + 1] + 1是因为假如longestLengthes[i]>longestLengthes[i + 1] + 1,那么显然longestLengthes[i + 1] >= longestLengthes[i] - 1 >longestLengthes[i + 1](整体不重复自然局部不会重复),这是不可能发生的。(如果对这部分不理解,可以枚举可能的情况,总共只有三种)转换成代码:

longestLengthes = int[s.length]

longestLengthes[s.length - 1] = 1

for(i = s.length - 2; i >= 0; i--)

  longestLengthes[i] = min(longestLengthes[i + 1] + 1, nextOccurance [i] - i)

之后遍历整个longestLengthes数组就可以找到最长的无重复子字符串的长度。

把上面两部分的代码整合,可以轻易得出整体的复杂度为O(n),其中n为传入字符串的长度。


最后给出整个实现代码,给有需要的人:

package cn.dalt.leetcode;

/**
 * Created by Administrator on 2017/6/4.
 */
public class LongestSubstringWithoutRepeatingCharacters {
    public static void main(String[] args) {
        String s = "yiwgczzovxdrrgeebkqliobitcjgqxeqhbxkcyaxvdqplxtmhmarcbzwekewkknrnmdpmfohlfyweujlgjf";
        System.out.println(new LongestSubstringWithoutRepeatingCharacters().lengthOfLongestSubstring(s));
        for(char c = 0; c < 256; c++)
        {
            System.out.println((int)c + ":" + c);
        }
    }

    int[] nextOccurIndexes = null;
    int[] registries = new int[1 << 8];

    public int lengthOfLongestSubstring(String s) {
        //Calculate all next occur indexes
        //nextOccurIndexes[i] is the minimun index of s which has properties that index > i && s[i] = s[index]
        int slength = s.length();
        if (slength == 0) {
            return 0;
        }
        nextOccurIndexes = new int[s.length()];
        for (int i = 0, bound = registries.length; i < bound; i++) {
            registries[i] = -1;
        }
        for (int i = 0, bound = s.length(); i < bound; i++) {
            int c = s.charAt(i);
            int registry = registries[c];
            if (registry != -1) {
                nextOccurIndexes[registry] = i;
            }
            registries[c] = i;
        }
        for (int registry : registries) {
            if (registry != -1) {
                nextOccurIndexes[registry] = slength;
            }
        }

        int[] longestNoneRepetitionSubstringLengthes = new int[s.length()];
        longestNoneRepetitionSubstringLengthes[s.length() - 1] = 1;
        int longestNoneRepetitionSubstringIndex = s.length() - 1;
        for (int i = s.length() - 2; i >= 0; i--) {
            int probablyMaxLength1 = longestNoneRepetitionSubstringLengthes[i + 1] + 1;
            int probablyMaxLength2 = nextOccurIndexes[i] - i;
            longestNoneRepetitionSubstringLengthes[i] = Math.min(probablyMaxLength1, probablyMaxLength2);
            longestNoneRepetitionSubstringIndex =
                    longestNoneRepetitionSubstringLengthes[i] > longestNoneRepetitionSubstringLengthes[longestNoneRepetitionSubstringIndex] ?
                            i : longestNoneRepetitionSubstringIndex;
        }
        return longestNoneRepetitionSubstringLengthes[longestNoneRepetitionSubstringIndex];
    }
}

Leetcode:Longest Substring Without Repeating Characters分析和实现的更多相关文章

  1. [LeetCode] Longest Substring Without Repeating Characters 最长无重复子串

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  2. leetcode: longest substring without repeating characters

    July 16, 2015 Problem statement: Longest Substring Without Repeating Characters Read the blog: http: ...

  3. LeetCode:Longest Substring Without Repeating Characters(最长不重复子串)

    题目链接 Given a string, find the length of the longest substring without repeating characters. For exam ...

  4. [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串

    Given a string, find the length of the longest substring without repeating characters. Example 1: In ...

  5. C++ leetcode Longest Substring Without Repeating Characters

    要开学了,不开森.键盘声音有点大,担心会吵到舍友.今年要当个可爱的技术宅呀~ 题目:Given a string, find the length of the longest substring w ...

  6. [LeetCode]Longest Substring Without Repeating Characters题解

    Longest Substring Without Repeating Characters: Given a string, find the length of the longest subst ...

  7. [LeetCode] Longest Substring Without Repeating Characters 最长无重复字符的子串 C++实现java实现

    最长无重复字符的子串 Given a string, find the length of the longest substring without repeating characters. Ex ...

  8. LeetCode——Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

  9. [Leetcode] Longest Substring Without Repeating Characters (C++)

    题目: Given a string, find the length of the longest substring without repeating characters. For examp ...

随机推荐

  1. Arcgis for Js实现graphiclayer的空间查询(续)

    上文中,实现了简单的针对graphiclayer的空间查询工作,在本节,将更加详细的介绍针对graphiclayer的空间查询.首先,空间查询的方式:提供多种类型的空间查询,包括点周边.线周边.面内等 ...

  2. 迭代器模式在 Java 容器中的实现

    迭代器接口是迭代器模式实现的精髓: public interface Iterator<E> { boolean hasNext(); E next(); ... } 假设某容器名为 Xx ...

  3. (一)java概述

    1.Java1995年斯坦福大学网络公司推出的一门高级语言.一种面向网络,完全的面向对象,完全可靠跨平台的语言.      java:一种面向对象的高级语言           将现实生活中的事物以及 ...

  4. 【占位】HihoCoder 1160 : 攻城略地(并查集好题)

    攻城略地 时间限制:2000ms 单点时限:1000ms 内存限制:256MB 描述 A.B两国间发生战争了,B国要在最短时间内对A国发动攻击.已知A国共有n个城市(城市编号1, 2, …, n),城 ...

  5. 剑指offer-第七章面试案例1(字符串转换为整型)

    //将字符串转换为整型 //思路:特殊的输入测试: //1,考虑字符串是否为空.2.字符串问空的时候的返回0,和真实的返回0直键的区别.3,字符串中出现0~9的字符处理 //4.字符串中出现*,¥等一 ...

  6. SqlServer 数据表数据移动

    描述:将Test1表中的数据放到Test2表中 1.Test2表不存在 select A,B,C insert into Test2 from Test1 select * into Test2 fr ...

  7. Hive中使用Python实现Transform时遇到Broken pipe错误排查

    Hive中有一表,列分隔符为冒号(:),有一列utime是Timestamp格式,需要转成Weekday存到新表. 利用Python写一个Pipeline的Transform,weekday.py的代 ...

  8. Cam350导入Allegro的*.rou文件

    如果生产allegro的生产文件有椭圆形钻孔,生成.rou.直接自动导入到cam350是没办法成功的. 以下说说本人的步骤.allegro里面的单位都是mm 在cam350的File-->Imp ...

  9. JS、Jquery获取浏览器和屏幕各种高度宽度

    网页可见区域宽:document.body.clientWidth网页可见区域高:document.body.clientHeight网页可见区域宽:document.body.offsetWidth ...

  10. tomcat部署去掉项目名称

    1.在tomcat下的conf路径找到server.xml文件. 2.找到Host如图 <Host name="localhost" appBase="webapp ...