算法系列——Longest Substring Without Repeating Characters

来源:互联网 发布:国家药监局数据查询 编辑:程序博客网 时间:2024/06/07 00:14

问题描述

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

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that
the answer must be a substring, “pwke” is a subsequence and not a
substring.

解题思路

滑动窗口+哈希表

采用双指针l,r [l,r]维护不重复字符串,哈希表记录 窗口中字符出现的频率。

程序实现

public class Solution {    public int lengthOfLongestSubstring(String s) {        int[] freq=new int[256];        int l=0,r=-1;        int result=0;        while(l<s.length()){            if(r+1<s.length()&&freq[s.charAt(r+1)]==0)                freq[s.charAt(++r)]++;            else                freq[s.charAt(l++)]--;            result=Math.max(result,r-l+1);        }        return result;    }}
阅读全文
0 0