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

  • 相关阅读:
    网站安全配置Nginx防止网站被攻击
    JAVA程序打包方法-挺好
    Kettle6.1连接MongoDB报错
    基于Rancher搭建Kubernetes
    Tomcat性能调优实战
    const int * 和 int * const 傻傻分不清楚
    洛谷P1028数的计算
    【转】sizeof()用法总结
    百练4103:踩方格(DFS)
    百练2815:城堡问题(DFS)
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607892.html
Copyright © 2020-2023  润新知