• 3. Longest Substring Without Repeating Characters java solutions


    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 subsequence and not a substring.

     1 public class Solution {
     2     public int lengthOfLongestSubstring(String s) {
     3         int n = s.length();
     4         int begin = 0, end = 0;
     5         boolean[] exist = new boolean[256];
     6         int maxlen = 0;
     7         while(end < n){
     8             if(!exist[s.charAt(end)]){
     9                 exist[s.charAt(end)] = true;
    10                 end++;
    11             }else{
    12                 while(s.charAt(begin) != s.charAt(end)){
    13                     exist[s.charAt(begin)] = false;
    14                     begin++;//下一次搜寻,应该跨过出现重复的地方进行,否则找出来的候选串依然有重复字符,且长度还不如上次的搜索。
    15                 }
    16                 begin++;
    17                 end++;
    18             }
    19             maxlen = Math.max(maxlen,end-begin);
    20         }
    21         return maxlen;
    22     }
    23 }

    使用begin和end两个下标来记录最长子串的开始和结束位置。时间复杂度O(n)

  • 相关阅读:
    Day-11 闭包和迭代器
    Day-01 Python基础
    Day-10 函数的进阶
    Day-09 初识函数
    Day-08 文件操作
    Day-07 基础数据类型补充 set集合 深浅拷贝
    Day-06 小数据池 再谈编码
    Day-05 基础数据类型字典dict
    Day-04 基础数据类型list, tuple
    NodeJs获取两个日期间的所有日期
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5623202.html
Copyright © 2020-2023  润新知