专栏名称: 每日一道算法题
学习算法是一种信仰,每天都需要坚持!
目录
相关文章推荐
算法与数学之美  ·  二级教授、大学原副校长,国务院特殊津贴获得者 ... ·  16 小时前  
算法与数学之美  ·  丘成桐任首任院长!顶尖大学成立新学院:8年制 ... ·  16 小时前  
九章算法  ·  Cruise被迫裁员50%!高额遣散费打脸科 ... ·  2 天前  
九章算法  ·  一年被裁两次,一个底层码农的大落大起 ·  2 天前  
51好读  ›  专栏  ›  每日一道算法题

[每日一题]3. Longest Substring Without Repeating Characters

每日一道算法题  · 公众号  · 算法  · 2017-10-12 22:54

正文

题目描述

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.


提示:提交代码后,需要用简洁的语言解释一下代码思路~ 谢谢


历史题目和总结见公众号「每日一道算法题」


https://leetcode.com/problems/longest-substring-without-repeating-characters/description/


难度:


Medium



解题思路



粗一看是dp,细一看是greedy


我们先从第一个字符开始,只要碰到已经出现过的字符我们就必须从之前出现该字符的index开始重新往后看。


例如‘xyzxlkjh’,当看到第二个‘x’时我们就应该从y开始重新往后看了。


那么怎么判断字符已经出现过了呢?我们使用一个hashmap,将每一个已经阅读过的字符作为键,而它的值就是它在原字符串中的index,如果我们现在的字符不在hashmap里面我们就把它加进hashmap中去,因此,只要目前的这个字符在该hashmap中的值大于等于了这一轮字符串的首字符,就说明它已经出现过了,我们就将首字符的index加1,即从后一位又重新开始读,然后比较目前的子串长度与之前的最大长度,取大者。



程序变量解释


  • -l(字母L) 代表目前最大子串的长度

  • start 是这一轮未重复子串首字母的index

  • maps 放置每一个字符的index,如果maps.get(s[i], -1)大于等于start的话,就说明字符重复了,此时就要重置 l(字母L)  和start的值了,

最后还要进行一次比较,因为最后一次没有比较,即 n - start 和 l (字母L) 的比较,这是最后一个round



python

class Solution(object):

def lengthOfLongestSubstring(self, s):

"""

:type s: str

:rtype: int

"""

l, start, n = 0, 0, len(s)

maps = {}

for i in range(n):

if maps.get(s[i], -1) >= start:

l = max(l, i - start)

start = maps.get(s[i]) + 1

maps[s[i]] = i

return max(l, n - start)





class Solution {

public int lengthOfLongestSubstring(String s) {

HashMap map = new HashMap ();

int l= 0;

int start = 0;

int n = s.length();

for (int i = 0; i < n; i++){

if(returnDef(map, s.charAt(i)) >= start){

l = Math.max(l, i-start);

start = map.get(s.charAt(i)) + 1;

}

map.put(s.charAt(i), i);

}

return Math.max(n-start,l);

}

public int returnDef(HashMap map, Character c){

if (map.get(c) == null){

return -1;

}

return map.get(c);

}

}







打赏作者



谢谢Keqi Huang的无私的总结,欢迎大家打赏。







请到「今天看啥」查看全文