package com.leetcode.lengthoflongestsubstring;
/**
* 题目:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 eg:"abcdabcbb" 结果是4 "bbbbb" 结果是1 思考:
* 用一个额外数组存储字符在字符串中出现的位置,大小为256.
* 采用滑动窗口的方法,设置窗口头尾两个指针,如果下一个是新字符,则数组向后存储,否则start更新为上次出现的位置。
*
* @author hexiaoli
*/
public class Solution {
public static int lengthOfLongestSubstring(String s) {
// 结果
int result = 0;
// 边界
if (s == null || s.length() <= 0) {
return result;
}
int[] pos = new int[256];
// 窗口指针
int start = 0;
int end = 0;
// 遍历字符串
while (end < s.length()) {
// 如果字符之前出现过,start更新为上一次字符出现过的位置。
if (pos[s.charAt(end)] > start) {
start = pos[s.charAt(end)];
}
// 向后遍历
pos[s.charAt(end)] = ++end;
// 更新最大值
if (result < end - start) {
result = end - start;
}
}
return result;
}
public static void main(String[] args) {
}
}