zoukankan      html  css  js  c++  java
  • [leetcode]3. Longest Substring Without Repeating Characters无重复字母的最长子串

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

    题意:

    给定一个字符串, 求其中无重复字母的最长子串

    Solution1:

    maintain a sliding window [start...i], making sure that each char in such window, its frequency is 1 (without Repeating chars)

    when one char's frequency > 1, there is repeating char, then move pointer start to find the next window

    code:

     1 /* 
     2    Time Complexity: O(n)
     3    Space Complexity: O(256)
     4 */
     5 class Solution {
     6     public int lengthOfLongestSubstring(String s) {
     7         // corner case 
     8         if( s == null || s.length() == 0) return 0;
     9         
    10         int[] map = new int[256];
    11         int result = 0;
    12         int start = 0;
    13         for(int i = 0; i < s.length(); i++){
    14             map[s.charAt(i)] ++;
    15             if(map[s.charAt(i)] > 1){
    16                 while(map[s.charAt(i)] > 1){
    17                     map[s.charAt(start)]--;
    18                     start++;
    19                 }
    20             } 
    21            result = Math.max(result, i - start + 1);   
    22         }
    23         return result;
    24     }
    25 }
  • 相关阅读:
    各种筛法与莫比乌斯反演
    欧拉函数技巧与学习笔记
    莫比乌斯函数与欧拉函数的单个值的快速求法
    最短路算法总结
    NOI2018网络同步赛游记
    中国剩余定理及其扩展学习笔记
    构造方法的格式
    private关键字
    成员变量和局部变量的区别
    数据加密代码实现
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9201944.html
Copyright © 2011-2022 走看看