题目描述:(中等难度)
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 subsequenceand not a substring.
题目解释:
给出一个字符串,求出没有相同字符的最大子串的长度。
题目解法:
1.我的解法。使用一个中间字符数组做标记,使用max标记最大长度;从头开始遍历每个字符,将该字符加入到中间字符数组中;再依次遍历后续的字符,如果后续的字符没有在中间字符数组中出现,那么将该字符加入到中间字符数组中,中间字符的有效长度 + 1,如果该有效长度大于最大长度,那么最大长度变成该中间字符的有效长度;直到遍历完毕。代码如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length() == 0) return 0;
int max = 1;
char[] array = s.toCharArray();
char[] temp = new char[array.length];
for(int i = 0;i<array.length;i++) {
temp[0] = array[i];
int tempLength = 1;
for(int j = i + 1;j < array.length;j++) {
boolean flag = true;
for(int k = 0;k < tempLength;k++) {
if(array[j] == temp[k]) {
flag = false;
break;
}
}
if(flag == true) {
temp[tempLength] = array[j];
tempLength++;
if(tempLength > max) max = tempLength;
} else break;
}
}
return max;
}
}