GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/code/lc3.java at master · mJackie/leetcode Expand file tree/ Copy pathlc3.javaMore file actions 38 lines (36 loc) · 1.34 KB / Copy pathlc3.javaFile metadata and controls38 lines (36 loc) · 1.34 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package code; /* * 3. Longest Substring Without Repeating Characters * 题意:找出字符串中没有重复字母的最大长度 * 难度:Medium * 分类:Hash Table, Two Pointers, String * 算法:两个指针,记录没有重复字母的子串的首和尾 * lc76 */ import java.util.HashMap; public class lc3 { public static void main(String[] args) { String s = "abba"; System.out.println(lengthOfLongestSubstring(s)); } public static int lengthOfLongestSubstring(String s) { HashMap<Character,Integer> hm = new HashMap<>(); int max = 0; int j = 0; for (int i = 0; i <s.length() ; i++) { if(hm.containsKey(s.charAt(i))) { j = Math.max(hm.get(s.charAt(i))+1,j); //if input="abbabc" //when i = 3, s.chatAt(3) == 'a' , //we will found last 'a' appears at index 0, //but we should not update j from 2 ('b') to 0 ('a'), //because here although the 'a' is in hashMap, but it appears before 'b'. } //i到j没有重复的字母,所以+1 //写到if外,因为可能该串本身就没有重复的字母,以及串首与串尾也要考虑 max = Math.max(i-j+1,max); hm.put(s.charAt(i), i); }; return max; } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |