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.
开始的思路是:先将字符存在map中,运用hashmap的key唯一性,和快速查找性,如果遇到重复的,则循环回退到第一次出现的位置的下一个位置继续循环。
由于map中会用到containsKey的方法增加了时间复杂度,因此超时了
public class Solution { public int lengthOfLongestSubstring(String s) { Map<Character,Integer> map = new HashMap<Character,Integer>(); char[] ch = s.toCharArray(); if(s.equalsIgnoreCase("")||s.isEmpty()||null==s) return 0; int re=0; int max=0; for(int i=0;i<ch.length;i++){ char c = ch[i]; if(map.containsKey(c)){ re=0; i=map.get(c); map = new HashMap<Character,Integer>(); }else{ map.put(c, i); re++; if(re>max) max=re; } } return max; } }
经过思考,想到这些字符都是存在于ASCII表中,那申明一个int[128]的数组,来存放,就会保证在O(1)的时间内获取到这个字符是否已经存在,和这个字符的上一个出现位置
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.equalsIgnoreCase("")||s.isEmpty()||null==s) return 0; int[] init = new int[128]; Arrays.fill(init, -1); char[] ch = s.toCharArray(); int re = 0; int max = 0; for(int i=0;i<ch.length;i++){ char c = ch[i]; if(init[c]!=-1){ re=0; i = init[c]; init = new int[128]; Arrays.fill(init, -1); }else{ init[c]=i; re++; if(re>max) max = re; } } return max; } }