zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    设计模式 之 单例模式
    leetcode 69 x 的平方根 牛顿迭代法
    leetcode 98 验证二叉搜索树
    leetcode 54 螺旋数组
    第一篇-python入门
    python-入门
    python
    线性判别分析LDA总结
    LDA
    线性判别分析(LDA)原理
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5623202.html
Copyright © 2011-2022 走看看