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.
The idea is to use a stringbuffer object sb to accept data, and compare whether the SB contains (S. substring (I, I + 1). If it contains, delete (0, index) from SB and then sb. append (S. substring (I, I + 1), calculate the count of the record length, and compare it with Max. Return 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;
Error:
Runtime Error Message: Line 4: java.lang.IndexOutOfBoundsException: start 0, end 1, s.length() 0Last executed input: ""
This is an error reported directly by sb. append (S, 0, 1) without judging S: Add judgment
if(s.length() == 0) { return 0; }
The following error occurs:
Input: "bpfbhmipx"Output: 6Expected: 7
Here I have added "bpfbhmipx" for testing:
System.out.println("delete: " + sb + "---index: " + index);System.out.println("append: " + sb);System.out.println("count: " + count + "--" + sb);
Find out the attachment in the Delete Code where the error occurred:
int index = sb.indexOf(s.substring(i, i+1));// System.out.println("delete: " + sb + "---index: " + index); sb.delete(0, index+1);
Index Returns a real index. to delete it, it should be (index + 1) in sb. Delete ).
Complete code:
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