题目:https://leetcode.com/problems/longest-substring-without-repeating-characters
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.
题目大意是获取传入字符串中最长不重复字符串的长度
解法:
建立一个256位大小的整型数组来代替哈希表,这样做的原因是ASCII表共能表示256个字符,所以可以记录所有字符。
/**获取传入字符串中最长不重复字符串的长度
* @param s 传入的字符串
* @return 最长不重复字符串的长度
*/
public static int lengthOfLongestSubstring(String s) {
int[] m = new int[256];
Arrays.fill(m, -1);
//最长不重复字符串的长度
int destLenth = 0;
//不重复字符串的最左侧起始位置
int startIndex = -1;
for (int i = 0; i < s.length(); ++i) {
//根据字符是否重复,来重置不重复字符串的最左侧起始位置
startIndex = Math.max(startIndex, m[s.charAt(i)]);
//在对应的字符asc编码位置进行下标标记
m[s.charAt(i)] = i;
//已有最大长度(字符重复前的最大长度)和现有的最大长度的比较,然后更新长度
destLenth = Math.max(destLenth, i - startIndex);
}
return destLenth;
}
参考自:http://blog.youkuaiyun.com/fightforyourdream/article/details/17860983