zoukankan      html  css  js  c++  java
  • leetcode

    题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

    题目要求:求出最长的不重复子串

    思路:

    1、采用map,遍历字符串,将每个字符put进map
    2、如果长度为1,直接输出1
    3、end-begin+1(注意+1)
    end为当前遍历到的位置,
    begin为重复位置+1
    4、在遍历字符串的时候,判断当前字符是否存在resultMap.containsKey(key),
    如果不存在,将其put进map,并维护end-begin+1
    如果存在,重置begin位置,计算长度
    (begin的位置判断:如果当前begin位置index比重复位置大,需要begin==当前begin位置index,否则等于重复位置)
    begin = begin > (resultMap.get(key)+1) ? begin : (resultMap.get(key)+1)
    长度维护:
    result = result > (end-begin+1) ? result : (end-begin+1);

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            char str[] = s.toCharArray();
            int len = str.length;
            if(len == 1 ){
                return 1;
            }else {
                //        int sum = 0;
                int result = 0;
                int begin = 0;
                int end = 0;
                Map<String,Integer> resultMap = new HashMap<String, Integer>();
                for(int i = 0; i<len; i++){
                    String key = str[i]+"";
                    end = i;
                    //未重复
                    if(!resultMap.containsKey(key)){
                        resultMap.put(key,i);
                        result = result > (end-begin+1) ? result : (end-begin+1);
                    }else { //遇到重复
    //                resultMap.clear();
                        begin = begin > (resultMap.get(key)+1) ? begin : (resultMap.get(key)+1);
                        result = result > (end-begin+1) ? result : (end-begin+1);
                        resultMap.put(key,i);
                    }
                }
    //            System.out.println(result);
                return result;
            }
        }
    }
    

      

  • 相关阅读:
    mongodb MongoDB 聚合 group
    mongo数据库的各种查询语句示例
    Web测试方法总结
    python + selenium 自动化测试框架
    selenium关于断言的使用
    JavaScript利用键盘方向键(上下键)控制表格行选中
    TestNG 入门教程
    selenium+python之 辨识alert、window以及操作
    Selenium WebDriver中鼠标事件
    JS-运动基础(一)
  • 原文地址:https://www.cnblogs.com/tonghao/p/9661144.html
Copyright © 2011-2022 走看看