标签:line tmp 算法实现 使用 abc 字符 class splay eating
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
【LeetCode】Longest Substring Without Repeating Characters
标签:line tmp 算法实现 使用 abc 字符 class splay eating
原文地址:http://www.cnblogs.com/jzdwajue/p/7219631.html