Longest Substring Without Repeating Characters

来源:互联网 发布:java各种排序算法 编辑:程序博客网 时间:2024/06/05 16:45

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.

题目的意思是给定一个字符串,找出最长的不重复的子串的长度。比如“abcabcbb”的最长的不重复的子串为“abc”其长度为3;“bbbbb”的最长的不重复的子串为“b”,其长度为1

思路:
遍历字符串s,如果s中当前字符与子串中字符重复,那么就先找到子串中与当前重复的字符的下标c,然后子串的开始位置current就应该为c+1

比如:s1=ebabcadefg
遍历s1 此时子串为eba,再往后,s1中当前字符为b与子串中的字符重复,那么先计算出此时子串的长度,更新result的值,然后找到子串中重复字符b的下标为1,那么就将子串的开始位置变为2,也就是子串再从a开始,因为如果子串中继续包括b的话会有重复的数字,不过在遍历s的过程中要不断的更新result的值,以便记录下最新的最大的不重复子串的长度。

注意:
1. 用一个数组来表示出现的字符的下标(由于ASCII码由8位表示,共可以表示256个字符,所以这个下标数组的长度为256),先将字符串s中的字符在下标数组中的值初始化为-1,比如若s中有‘a’,‘a’的ASCII码为97,那么就有hash[97]=-1
2. 用current表示当前子串的第一个字符的下标,在current之前的都是无效的,current初始值为0。 用result来记录当前算得的最长的不重复的子串的长度。

public class Solution {    public int lengthOfLongestSubstring(String s) {            int result = 0;        int current = 0;        int strLength = s.length();        // hash数组是用来s中字符的下标        int[] hash = new int[256];        for (int i = 0; i < strLength; i++)            hash[s.charAt(i)] = -1;        for (int i = 0; i < strLength; i++) {            // 说明出现了重复的字符            if (hash[s.charAt(i)] >= current) {                result = Math.max(result, i - current);                current = hash[s.charAt(i)] + 1;                hash[s.charAt(i)] = i;            }            // 若没有出现重复的数字那就更新不重复字符串的长度,并更新hash表            else {                result = Math.max(result, i - current + 1);                hash[s.charAt(i)] = i;            }        }        return result;    } }
0 0
原创粉丝点击