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

  • 相关阅读:
    数据结构之数组
    数据结构之链表
    MongoDB使用笔记
    数据结构之ArrayList
    java设计模式之--装饰者模式
    JAVA设计模式之--模板方法模式
    HashTable、HashMap、ConcurrentHashMap源码分析
    Docker使用笔记
    First-blog:解决mybatis 用mysql进行模糊搜索时,查不了中文问题
    css cursor: url() 使用火狐浏览器问题,鼠标没有效果
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607892.html
Copyright © 2011-2022 走看看