Longest Substring Without Repeating Characters

来源:互联网 发布:无网络远程攝像头 编辑:程序博客网 时间:2024/06/11 17:53

题目: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.csdn.net/fightforyourdream/article/details/17860983