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

    问题描述

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    解决思路

    双指针 + HashSet

    前后两个指针,开始时均指向第一个元素,将第一个元素加入HashSet中。

    然后移动后指针,只要set中不包含指向元素则移动后指针,不断记录两个指针间的最大长度差(即为不重复字符的字符串)。

    时间复杂度和空间复杂度均为O(n).

    程序

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            
            int len = s.length();
            int max = 1;
            HashSet<Character> set = new HashSet<>();
            int low = 0, high = 0;
            
            while (high < len) {
    			char c = s.charAt(high);
    			if (!set.contains(c)) {
    				set.add(c);
    				++high;
    				max = Math.max(max, high - low);
    				continue;
    			}
    			char t = s.charAt(low);
    			set.remove(t);
    			++low;
    		}
            
            return max;
        }
    }
    
  • 相关阅读:
    针对web高并发量的处理
    外边距合并,外边距折叠
    cookie 和session 的区别:
    ng-if ng-show ng-hide 的区别
    JavaScript中的arguments,callee,caller
    git常见命令
    jQuery中.bind() .live() .delegate() .on()的区别
    为什么要使用sass
    js兼容性记录
    poj1004
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4721044.html
Copyright © 2011-2022 走看看