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 asubstring,"pwke"
is a subsequence and not a substring.
Subscribe to see which companies asked this question
package temp;
/**
*
* @author Mouse
*
*/
public class Solution {
public static int lengthOfLongestSubstring(String s) {
if (s.length() == 0)
return 0;
if (s.length() == 1) {
return 1;
}
// 下面处理的是至少含2个元素的字符串
char[] c = s.toCharArray();
int start = 0;
int end = 0;
int count = 0;
// 下面的for是为了计算有多少个重复的元素并进行切分
// count得到我才知道我new多少个空间去存放数据
for (int i = end; i < c.length; i++) {
for (int j = start; j < i; j++) {
if (c[i] == c[j]) {
start = j + 1;
end = i - 1;
count++;
}
}
}
// 恢复start和end的原状。我在这里只是不想重新申请新的变量,毕竟变量已经够用了
start = 0;
end = 0;
int[] data = new int[count + 1];
int mcount = count;
count = 0;
int ka = 0;
int kb = 0;
for (int i = end; i < c.length; i++) {
for (int j = start; j < i; j++) {
if (c[i] == c[j]) {
// System.out.print("开始位置:" + start);
ka = start;
start = j + 1;
end = i - 1;
kb = end;
// System.out.println("结束位置:" + end);
data[count] = kb - ka + 1;
count++;
}
}
// 当end失效时即i到达s字符串最后一处,却没有找到与前面相同的元素
if (i == s.length() - 1) {
data[mcount] = i - start + 1;
}
}
// 找最大的数
if (count == 0) {
return s.length();
}
int max = data[0];
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
public static void main(String[] args) {
String a = "c";
int data = lengthOfLongestSubstring(a);
System.out.println(data);
}
}
以上代码我写得很清楚,我就不解释了哈
大家可以查看网上其它的做法:http://www.programcreek.com/2013/02/leetcode-longest-substring-without-repeating-characters-java/