zoukankan      html  css  js  c++  java
  • 【LeetCode3】Longest Substring Without Repeating Characters★★

    题目描述:

    解题思路:

       借用网上大神的思想:the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.

      大意:基本思想是,用一个hashmap存储字符串,把字符串的每一个字符当作key,字符所在的位置作为value,并维护两个指针,两个指针之间就是不存在重复字符的字串,而此题求的是满足这样要求的最大字串。然后,移动右指针遍历字符串,同时更新hashmap。如果遍历到的字符已存在于hashmap,就移动左指针到最后一次出现该字符的右边一个位置。注意,两个指针都只能向右移动,不能回退。

      以字符串abbc为例:

    Java代码:

     1 import java.util.HashMap;
     2 import java.util.Map;
     3 
     4 public class LeetCode371 {
     5     public static void main(String[] args) {
     6         String s="abba";
     7         System.out.println(s+"最长不存在重复字符的字串长度是:"+new Solution().lengthOfLongestSubstring(s));
     8         }
     9 }
    10 class Solution {
    11 public int lengthOfLongestSubstring(String s) {
    12         Map<Character,Integer> map=new HashMap<Character,Integer>();
    13         int max=0;
    14         for(int left=0,right=0;right<s.length();right++){
    15             if(map.containsKey(s.charAt(right)))
    16                 left=Math.max(left,map.get(s.charAt(right))+1);
    17             map.put(s.charAt(right), right);
    18             max=(right-left+1)>=max?(right-left+1):max;
    19         }
    20         return max;
    21     }
    22 }

    程序结果:

  • 相关阅读:
    数据库的左右表连接
    数据库索引-索引的优点、缺点、分类、不走索引的情况
    selenium中日期控件的操作方法
    esdoc 自动生成接口文档介绍
    css设置背景图(背景图太大导致图片显示不全)
    k8s调度器及调度队列源码分析
    MIT6.824 2020 Lab1 MapReduce 实现
    git命令
    python3.6、3.9多版本安装共存
    使用蓝鲸平台登录态验证接入第三方系统
  • 原文地址:https://www.cnblogs.com/zhangboy/p/6473873.html
Copyright © 2011-2022 走看看