Given a string, find the length of the longest substring without repeating characters.
Example 1:
代码语言:javascript复制Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
代码语言:javascript复制Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
代码语言:javascript复制Input: "pwwkew"
Output: 3
Explanation: 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.
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例 1:
代码语言:javascript复制输入: "abcabcbb"
输出: 3
解释: 无重复字符的最长子串是 "abc",其长度为 3。
示例 2:
代码语言:javascript复制输入: "bbbbb"
输出: 1
解释: 无重复字符的最长子串是 "b",其长度为 1。
示例 3:
代码语言:javascript复制输入: "pwwkew"
输出: 3
解释: 无重复字符的最长子串是 "wke",其长度为 3。
请注意,答案必须是一个子串,"pwke" 是一个子序列 而不是子串。
代码语言:javascript复制class Solution {
public int lengthOfLongestSubstring(String s) {
char[] c = s.toCharArray();
List<Character> list = new LinkedList<Character>();
int max = 0;
for (int i = 0; i < c.length; i) {
if (list.contains(c[i])) {
max = Math.max(max, list.size());
list.remove(0);
while (list.contains(c[i])) {
list.remove(0);
}
list.add(c[i]);
} else {
list.add(c[i]);
}
}
max = Math.max(max, list.size());
return max;
}
}
迅雷笔试题2,采用leetcode原题。
Debug code in playground:
代码语言:javascript复制class Solution {
public int lengthOfLongestSubstring(String s) {
char[] c = s.toCharArray();
List<Character> list = new LinkedList<Character>();
int max = 0;
for (int i = 0; i < c.length; i) {
if (list.contains(c[i])) {
max = Math.max(max, list.size());
list.remove(0);
while (list.contains(c[i])) {
list.remove(0);
}
list.add(c[i]);
} else {
list.add(c[i]);
}
}
max = Math.max(max, list.size());
return max;
}
}
public class MainClass {
public static String stringToString(String input) {
return JsonArray.readFrom("[" input "]").get(0).asString();
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
String s = stringToString(line);
int ret = new Solution().lengthOfLongestSubstring(s);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}