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

  • 相关阅读:
    为什么需要Docker?
    一分钟学会《模板方法模式》
    2018再见|2019你好
    三分钟学会《门面模式》
    策略模式原来这么简单!
    外行人都能看得懂的机器学习,错过了血亏!
    我是如何将博客转成PDF的
    面试前必须知道的MySQL命令【explain】
    count(*)、count(1)和count(列名)的区别
    Linux shell去除字符串中所有空格
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607892.html
Copyright © 2011-2022 走看看