国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

LeetCode-LongestSubstringWithoutRepeatingCharacters

2019-11-14 14:52:30
字體:
來源:轉載
供稿:網友

題目:

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.

思路:

1) 兩個for循環,用map存訪問過的字母,遇到相同的就停止,然后再從這個相同字母的下一個字母開始。超時了。

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)對方法一的簡化,保持重復元素的上一個位置,往前挪動,不斷計算

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));    }}

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 策勒县| 石台县| 阳城县| 六安市| 淮北市| 阳春市| 新乡县| 化州市| 浙江省| 黄石市| 洪江市| 孟村| 岢岚县| 嵊州市| 湛江市| 射洪县| 巫山县| 衡山县| 湖州市| 天镇县| 洪雅县| 陕西省| 六安市| 凤凰县| 诸暨市| 新沂市| 威宁| 连云港市| 淄博市| 隆德县| 仪征市| 阜康市| 丰原市| 张掖市| 巴林左旗| 合江县| 嘉义县| 贵港市| 紫阳县| 苏尼特右旗| 犍为县|