标签:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
想法是使用一个StringBuffer对象sb来接受数据,每次比较sb中是否contains(s.substring(i, i+1)),假如包含,那么从sb中delete(0, index),然后sb.append(s.substring(i, i+1)),对于记录长度的count进行计算,然后与max进行比较,返回max即可。
public int lengthOfLongestSubstring(String s) { StringBuffer sb = new StringBuffer(); sb.append(s, 0, 1); int length = s.length(); int max = 1, count = 1; for(int i = 1; i < length; i++) { if(new String(sb).contains(s.substring(i, i+1))) { int index = sb.indexOf(s.substring(i, i+1)); sb.delete(0, index); count = count - index; } else { sb.append(s, i, i+1); count++; } if(count > max) { max = count; } } return max;
得到错误:
Runtime Error Message: Line 4: java.lang.IndexOutOfBoundsException: start 0, end 1, s.length() 0 Last executed input: ""
这个是没有判断s,就直接进行sb.append(s, 0, 1)报的错误:加入判断
if(s.length() == 0) { return 0; }
然后出现的错误:
Input: "bpfbhmipx" Output: 6 Expected: 7
这里我加入了”bpfbhmipx”之后进行测试:
System.out.println("delete: " + sb + "---index: " + index); System.out.println("append: " + sb); System.out.println("count: " + count + "--" + sb);
找出错误发生在delete代码附件:
int index = sb.indexOf(s.substring(i, i+1)); // System.out.println("delete: " + sb + "---index: " + index); sb.delete(0, index+1);
index返回的是真是的index,要把它删除,在sb.delete()中应该是(index+1)。
完整代码:
public int lengthOfLongestSubstring(String s) { StringBuffer sb = new StringBuffer(); if(s.length() == 0) { return 0; } sb.append(s, 0, 1); int length = s.length(); int max = 1, count = 1; for(int i = 1; i < length; i++) { if(new String(sb).contains(s.substring(i, i+1))) { int index = sb.indexOf(s.substring(i, i+1)); // System.out.println("delete: " + sb + "---index: " + index); sb.delete(0, index+1); sb.append(s.substring(i, i+1)); // System.out.println("append: " + sb); count = count - index; } else { sb.append(s, i, i+1); count++; } // System.out.println("count: " + count + "--" + sb); if(count > max) { max = count; } } return max; }
LeetCode:Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/dslover/p/4309032.html