zoukankan      html  css  js  c++  java
  • Java [leetcode 3] 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.

    解题思路:

    思路与第一题有点类似,同样是用HashMap来存储数组值和下标,其中数组值为HashMap中的key值,数组下标为HashMap中的value值。不同的是,这次需要一个类似于C++中的指针来指明字串的起点。也就是说,每次添加一个key值时,是从指针往后的范围比较是否重复的,如果重复的话则将指针移动到该值下一个下标处,否则往HashMap中继续添加键值并往后比较。

    代码如下:

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
    		Map<Character, Integer> map = new HashMap<Character, Integer>();
    		int length = 1;
    		int sum = 0;
    		int pointer = 0;
    
    		if (s == null || s.length() == 0)
    			return 0;
    
    		for (int i = 0; i < s.length(); i++) {
    			if (map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) >= pointer) {
    				Integer tmp = map.get(s.charAt(i));
    				sum = i - pointer;
    			    length = Math.max(sum, length);
    				pointer = tmp + 1;
    				map.put(s.charAt(i), i);
    
    			} else {
    				map.put(s.charAt(i), i);
    			}
    		}
    		
    		length = Math.max(s.length() - pointer, length);
    
    		return length;
    	}
    }
    
  • 相关阅读:
    14.RabbitMQ
    13.跨域
    12.EF
    11.Redis
    GitHub获取用户ID
    10.AOP
    第26节课:pytest结合Allure操作
    第25节课:pytest测试框架
    第二十四节课:requests爬虫实战
    第二十三节课:正则表达式re模块:
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4455792.html
Copyright © 2011-2022 走看看