LeetCodeLongest Substring Without Repeating Characters
Posted jzdwajue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCodeLongest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
问题描写叙述
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.
Input:abcabcbb
Output:3
意:查找给定字符串中最长的无反复字符的子串
算法思想
对于字符串
S<a1,a2,a3,a4,a3> ,假设我们从左向右扫描字符串,那么当遇到第二个a3 时,对于a4 及其之前的全部子串的长度一定小于等于a4 。所以不必要每次从头查找子串。
假设没有反复字符。那么i=0。j=n, 长度为j-i+1
假设存在反复字符,那么长度为j-i(不包括反复字符本身),然后我们将i更新为反复字符中的第一个,上例中当遇到第二个a3 时,i=2。
假设我们使用hashmap推断反复字符的出现,须要推断反复字符是否出如今i与j之间。
算法实现
import java.util.HashMap;
public class Solution {
public static int lengthOfLongestSubstring(String s) {
int i = 0;
int j = 0;
int loc = 0;
int nowCount = 0, tmpCount = 0;
HashMap<Character, Integer> holder = new HashMap<Character, Integer>();
int n = s.length();
while (j < n) {
Character c = s.charAt(j);
if (!holder.containsKey(c) || (loc = holder.get(c)) < i) {
tmpCount = j - i + 1;
} else {
tmpCount = j - i;
i = loc + 1;
}
nowCount = tmpCount > nowCount ? tmpCount : nowCount;
holder.put(c, j);
j++;
}
return nowCount;
}
public static void main(String[] args) {
String s = "abcabc";
System.out.println(lengthOfLongestSubstring(s));
}
}
算法时间
T(n) = O(n);//忽略hash查找的时间
演示结果
3
以上是关于LeetCodeLongest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章
LeetCodeLongest Substring Without Repeating Characters
LeetcodeLongest Palindromic Substring
LeetCodeLongest Substring Without Repeating Characters 解题报告