Leetcode:3. Longest Substring without repeating Characters (Java)

Source: Internet
Author: User

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

Topic:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "ABCABCBB", the answer is "ABC" and 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 to be a substring, "Pwke" are a subsequence and not a substring.

Analytical:

Use HashMap to store not repeating substrings, key is a character, value is the position of this character. Traversing backwards, as long as there is no current character in the map, it is added to the map. and add the substring length to one. If the current character already appears in the map, get the position of this character in the map, clear this position and all keys before it. The substring is recalculated after this position, ensuring that the substring is not duplicated.


Java code implementation:

public class Solution {
public int lengthoflongestsubstring (String s) {
if (s = = null) return 0;
Hashmap<character, integer> map = new Hashmap<character, integer> ();
int start = 0;
int maxlen = 0;
int len = 0;
for (int i = 0; i < s.length (); i++) {
if (!map.containskey (S.charat (i))) {
len++;
if (Len > maxlen) maxlen = len;
Map.put (S.charat (i), i);
}else{
int index = Map.get (S.charat (i));
for (int j = start; J <= Index; j +) {
Map.Remove (S.charat (j));
}
Map.put (S.charat (i), i);
start = index+1;
len = I-index;
}
}
return maxlen;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.