zoukankan      html  css  js  c++  java
  • leetCode 3. Longest Substring Without Repeating Characters

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

    Example 1:

    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3. 
                 Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    定义两个辅助数组:
      last:在串0到(i-1)中,i位置字符最近出现的位置;
      res:存放以i位置字符结尾的最长互不重复的子串长度;
     1 class Solution8 {
     2     public int lengthOfLongestSubstring(String s) {
     3         if (s.length() < 1) return 0;
     4         if (s.length() == 1) return 1;
     5         int[] last = new int[s.length()];//存放在串0到(i-1)中,i位置字符最近出现的位置
     6         int[] res = new int[s.length()];//存放以i位置字符结尾的最长互不重复的子串长度
     7         int max = 1;
     8         Map<Character, Integer> map = new HashMap<>();
     9         for (int i = 0; i < s.length(); i++) {
    10             Integer lastLoc = map.get(s.charAt(i));
    11             if (lastLoc != null) {
    12                 last[i] = lastLoc;
    13             }else {
    14                 last[i] = -1;
    15             }
    16             map.put(s.charAt(i), i);
    17         }
    18 
    19         res[0] = 1;
    20         for (int i = 1; i < s.length(); i++) {
    21             if (last[i] < i - 1 - res[i-1]){
    22                 res[i] = res[i-1] + 1;
    23             }else {
    24                 res[i] = i - last[i];
    25             }
    26             max = (max < res[i]) ? res[i] : max;
    27         }
    28         return max;
    29     }
    30 }
  • 相关阅读:
    项目经验总结
    聚合,组合之间的关系(aggregate,composite)
    做策划方案遇到问题
    给公司员工上的培训1——微观规范
    关于Oracle的简单导入导出
    SVN服务管理配置(原创,引用请注明出处)
    面向功能开发一点经验
    SourceMonitor使用手记
    泡泡、搜房、方正我该如何选择
    Excel 关联 合并 上海
  • 原文地址:https://www.cnblogs.com/yfs123456/p/10910809.html
Copyright © 2011-2022 走看看