zoukankan      html  css  js  c++  java
  • 3 Longest Substring Without Repeating Characters(medium)

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequenceand not a substring.

    给定一个字符串,找到最长子串的长度,而不重复字符。

    例子:

    给定“abcabcbb”,答案是“abc”,长度为3。

    给定“bbbbb”,答案是“b”,长度为1。

    给定“pwwkew”,答案是“wke”,长度为3.请注意,答案必须是子字符串,“pwke”是子序列,而不是子字符串。

     

    /*
    * 对每个字符向后遍历如果字符没出现过加入字符串,若出现过使用Hash记录长度
    * Hash<字符,长度>
    * 时间复杂度O(n^2)
    */
    private int getLengthByHash(String str){
    int res = 0, length = str.length();
    Map<Character,Integer> map = new HashMap<>();
    for(int i = 0 ; i < length ; i++){
    StringBuffer temp = new StringBuffer(String.valueOf(str.charAt(i)));
    for(int j = i+1 ; j < length ; j++){
    if(temp.indexOf(String.valueOf(str.charAt(j))) == -1){
    temp.append(String.valueOf(str.charAt(j)));
    }else{
    int key = str.charAt(i),value = temp.length();
    if(map.containsKey(key)){
    value = Math.max(value, map.get(key));
    }
    map.put(str.charAt(i),value);
    break;
    }
    }
    }
    for(Character key:map.keySet()){
    res = Math.max(res, map.get(key));
    }
    return res;
    }

    /*
    * Hash<字符,下表>
    * 判断Hash中是否包含字符,若否dp[i] = dp[i-1] + 1 若是 dp[i] = i - 上次出现过的下标
    * 时间复杂度O(n)
    */
    private int getLengthByHashAndDP(String str){
    int res = 0, length = str.length();
    Map<Character,Integer> map = new HashMap<>();
    map.put(str.charAt(0), 0);
    int dp [] = new int [length];
    dp[0] = 1;
    for(int i = 1; i < length;i++){
    char key = str.charAt(i);
    if(!map.containsKey(key)){
    dp[i] = dp[i-1] + 1;
    }else{
    dp[i] = i - map.get(key);
    map.put(key, i);
    }
    map.put(key, i);
    res = Math.max(res, dp[i]);
    }
    return res;
    }

  • 相关阅读:
    H5中https://j.map.baidu.com/e7/M6hJ的地址是如何生成的
    转义符
    vue-json-excel导出数字字符串转为科学计数法问题和文件格式问题
    高级JavaScript(4)RegExp,正则表达式
    js7种数据类型
    gulp自动化打包及静态文件自动添加版本号
    解决——CSS :before、:after ,当content使用中文时有时候会出现乱码
    【移动端】移动端点击可点击元素时,出现蓝色默认背景色
    我去!爬虫遇到字体反爬,哭了
    实战|教你用Python玩转Mysql
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607892.html
Copyright © 2011-2022 走看看