[LeetCode] Longest Substring Without Repeating Characters

来源:互联网 发布:window7怎么连接网络 编辑:程序博客网 时间:2024/06/05 06:31

题目:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


思路:

暴力做法是找到s的每一个子串,再对子串进行重复字符检测,但是肯定不会通过LeetCode OJ的测试。基本思路还是循环,但是在遍历和判断是否有重复字符的时候,选择用空间换时间的策略,引入两个数组exist[]和position[],分别存储的信息是该字符是否出现在当前子串中以及出现的下标。需要注意的是字符集不仅仅是{a,b,c……,z},可能包括特殊字符,这里考虑的是ASCII字符集。


代码

public class Solution {    public int lengthOfLongestSubstring(String s) {        int start = 0,maxLen = 0;        int[] position = new int[255];        boolean[] exist = new boolean[255];                if(s == null || s.equals(""))            return 0;                for(int i = 0;i < 255;i++){            position[i] = -1;            exist[i] = false;        }                for(int i = 0;i < s.length();i++){            if(!exist[s.charAt(i) - ' ']){                position[s.charAt(i) - ' '] = i;                exist[s.charAt(i) - ' '] = true;                maxLen = ((i - start) + 1 > maxLen) ? (i - start) + 1 : maxLen;            }            else{                for(int j = start;j < i;j++){                    exist[s.charAt(j) - ' '] = false;                }                               start = position[s.charAt(i) - ' '] + 1;                exist[s.charAt(start) - ' '] = true;                position[s.charAt(start) - ' '] = start;                i = start;           }        }        return maxLen;    }}


0 0
原创粉丝点击