【LeetCode】3.Longest Substring Without Repeating Characters 最长无重复子串

时间:2023-12-10 10:48:44

题目:

  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.

思路:

  初始字符上一次出现的位置-1,初始子串开始位置-1。对字符串中每个字符元素遍历,判断更新子串的开始位置及最大长度,循环结束后 返回最大长度max. 

public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] local=new int[128];
int index=-1;
int max=0; for(int a=0;a<local.length;a++){
local[a]=-1;
} for(int i=0;i<s.length();i++){ if(local[(int)s.charAt(i)]>index){
index=local[(int)s.charAt(i)];
} if(i-index>max){
max=i-index;
} local[(int)s.charAt(i)]=i;
} return max;
}
}