Given a string, find the length of the longest substring without repeating characters.
创新互联是一家专业提供横山企业网站建设,专注与成都网站建设、网站设计、H5高端网站建设、小程序制作等业务。10年已为横山众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。
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.
-
public class T {
-
public static void main(String[] args) {
-
String s1 = "pwwkew";
-
String s2 = "abcabcbb";
-
String s3 = "dvdf";
-
String s4 = "bbbb";
-
System.out.println(lengthOfLongestSubstring(s1));
-
-
}
-
-
public static int lengthOfLongestSubstring(String s) {
-
int maxlength = 0;
-
int leftIndex = 0;
-
int rightIndex = 0;
-
while (rightIndex < s.length()) {
-
char target = s.charAt(rightIndex);
-
int mark = -1;
-
for (int i = leftIndex; i < rightIndex; i++) {
-
if (s.charAt(i) == target) {
-
mark = i + 1;
-
break;
-
}
-
}
-
-
if (mark != -1) {
-
if ((rightIndex - leftIndex) > maxlength) {
-
maxlength = (rightIndex - leftIndex);
-
}
-
leftIndex = mark;
-
rightIndex = mark;
-
-
} else {
-
rightIndex++;
-
}
-
}
-
if ((rightIndex - leftIndex) > maxlength) {
-
maxlength = (rightIndex - leftIndex);
-
}
-
return maxlength;
-
}
-
}
另附网上的答案一则.
http://www.cnblogs.com/grandyang/p/4480780.html
-
public class Solution {
-
public int lengthOfLongestSubstring(String s) {
-
int[] m = new int[256];
-
Arrays.fill(m, -1);
-
int res = 0, left = -1;
-
for (int i = 0; i < s.length(); ++i) {
-
left = Math.max(left, m[s.charAt(i)]);
-
m[s.charAt(i)] = i;
-
res = Math.max(res, i - left);
-
}
-
return res;
-
}
-
}
网站名称:LongestSubstringWithoutRepeatingCharacters
当前链接:
http://kswsj.cn/article/ppdddg.html