题目
给出一个字符串,求其最长的、不包含重复字符的子串。
例子:"abcabcbb",答案是 3. "bbbbb",答案是1.
思路
将字符串转换为数组存储(JAVA)。定义变量start指向子串的开头,end指向子串的结尾。start初始=0.end初始=1。end从1到字符串最后一个元素遍历,如果其前边的字符有和它重复的,则更新start变量为重复字符的下一个位置。期间,没当end或start有变化则计算字符串的长度,与当前记录的最大值比较,更新最大值。
代码
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) return 0;
char[] arr = s.toCharArray(); //获取字符数组
int start = 0,ans = 1;
for(int end = 1; end < arr.length; end++) {
for(int j = start; j < end; j++) {
if(arr[j] == arr[end]) {
start = j + 1;
}
}
ans = (end - start + 1 > ans)?(end - start + 1):ans;
}
return ans;
}
//测试
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.lengthOfLongestSubstring("abcabcbb"));
System.out.println(solution.lengthOfLongestSubstring("bbbbb"));
System.out.println(solution.lengthOfLongestSubstring("pwwkew"));
System.out.println(solution.lengthOfLongestSubstring("aaaaaaaa"));
System.out.println(solution.lengthOfLongestSubstring("abcdbabcde"));
System.out.println(solution.lengthOfLongestSubstring(""));
System.out.println(solution.lengthOfLongestSubstring(null));
System.out.println(solution.lengthOfLongestSubstring("aaaaabbbbb"));
}
}
网友评论