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

  • 相关阅读:
    SQL Server 循环插入数据
    转:Visual Studio 打开程序提示仅我的代码怎么办
    DevExpress XAF 访问当前视图中选定的对象
    DevExpress安装
    待定位的小bug
    easyui datagrid的toolbar 按钮可以像linkbutton一样设置使能状态
    使用jquery同时设置两个对象的method为同一函数
    首页变黑白的办法
    关于jQueryEasyUI DateBox的基本使用
    好东西分享兼备忘
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607892.html
Copyright © 2011-2022 走看看