11-line simple Java solution, O(n) with explanation
the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substr
the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward. \n\n       public int lengthOfLongestSubstring(String s) {\n            if (s.length()==0) return 0;\n            HashMap<Character, Integer> map = new HashMap<Character, Integer>();\n            int max=0;\n            for (int i=0, j=0; i<s.length(); ++i){\n                if (map.containsKey(s.charAt(i))){\n                    j = Math.max(j,map.get(s.charAt(i))+1);\n                }\n                map.put(s.charAt(i),i);\n                max = Math.max(max,i-j+1);\n            }\n            return max;\n        }
[]