【字符串&最长无重复子串】Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝网红直播费用 编辑:程序博客网 时间:2024/05/17 08:40

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.

题意:求出最长的无重复子串的长度

解法:扫描字符串,sIndex表示扫描过程中当前最长无重复子串的首字符后一位的下标值(所以初始为-1),table[s.charAt(i)]表示字符s.charAt(i)上一次在字符串中出现的位置

——》若该字符串上一次出现的下标table[x]大于sIndex,则sIndex应该重置为当前遍历字符的前一次位置,即将无重复字符串的首字符设为table[x]+1所在位置

public class Solution {    public int lengthOfLongestSubstring(String s) {        int [] table = new int[256];        for(int i=0; i<table.length; i++) table[i] = -1;                int sIndex = -1;        int max = 0;        for(int i=0; i<s.length(); i++){            int t = table[s.charAt(i)];            sIndex = Math.max(sIndex, t);//每次重置无重复子串的首字符下标            max = Math.max(max, i-sIndex);//每次都重置无重复子串最大长度            table[s.charAt(i)] = i;        }        return max;    }}


0 0
原创粉丝点击