LeetCode, leetcodeoj
Question:
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.
Ideas:
1) for two for loops, use the map to store the accessed letters, stop when the same is encountered, and then start from the next letter of the same letter. Timeout.
package string;import java.util.HashMap;public class LongestSubstringWithoutRepeatingCharacters { public int lengthOfLongestSubstring(String s) { int len; if (s == null || (len = s.length()) == 0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max = 0; for (int i = 0; i < len; ++i) { map.put(s.charAt(i), i); for (int j = i + 1; j < len; ++j) { if (!map.containsKey(s.charAt(j))) { map.put(s.charAt(j), j); } else { i = map.get(s.charAt(j)); break; } } int count = map.size(); if (count > max) { max = count; } map.clear(); } return max; } public static void main(String[] args) { // TODO Auto-generated method stub String s = "abcabcbb"; LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters(); System.out.println(l.lengthOfLongestSubstring(s)); }}
2) simplify method 1, keep the previous position of the repeating element, move forward, and constantly calculate
package string;import java.util.HashMap;public class LongestSubstringWithoutRepeatingCharacters { public int lengthOfLongestSubstring(String s) { int len; if (s == null || (len = s.length()) == 0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max = 0; int lastIndex = -1; for (int i = 0; i < len; ++i) { char c = s.charAt(i); if (map.containsKey(c) && lastIndex < map.get(c)) { lastIndex = map.get(c); } if (i - lastIndex > max) max = i - lastIndex; map.put(c, i); } return max; } public static void main(String[] args) { // TODO Auto-generated method stub String s = "abcabcbb"; LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters(); System.out.println(l.lengthOfLongestSubstring(s)); }}