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

    本问题是求最长不重复子串。

    给出一种方法:

    例如:aplsdfgsjiuk,设置一个最长子串的起始位和结束位,a为起始位,b为结束位,当遍历aplsdfg时,下一位s重复,所以可以从d为起始位置在遍历。

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            
             boolean []arr = new boolean[256];
             for(int i = 0; i < 256; i++)
             {
                 arr[i] = false;
             }
             
             int a = 0;//记录开始位置
             int b = 0;//记录子串的结束位置 
             int maxlength = 0;
             
             while(b < s.length())
             {
                 if(!arr[s.charAt(b)])
                 {
                     arr[s.charAt(b)] = true;// 访问过了 
                     b++;
                 }
                 
                 else
                 {
                     while(s.charAt(a) != s.charAt(b))
                     {
                         arr[s.charAt(a)] = false;
                         a++;
                     }
                     
                     a++;
                     b++;
                     
                 }
                 
                 maxlength = (maxlength > (b-a))? maxlength:(b-a);
             }
             
             return maxlength;
            
            
        }
    }

      时间复杂度为O(n)。

  • 相关阅读:
    typescript-定义静态类型和对象类型
    typescript-全局安装
    Cube-ui的使用
    mobx-react
    Calatan Number
    快速排序
    Boyer-Moore
    优先级队列
    PointNet环境搭建
    h5py库
  • 原文地址:https://www.cnblogs.com/zyqBlog/p/5911949.html
Copyright © 2011-2022 走看看