3.Longest Substring Without Repeating Characters

来源:互联网 发布:linux 卸载svn 编辑:程序博客网 时间:2024/06/09 21:35

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

  • 题目含义:给定一个字符串,找出最长非重复的子串

  • 思路:其基本思想是保留一个散列表,它将字符串中的字符存储为键,并将它们的位置存储为值,并保留定义最大子字符串的两个指针。 移动右边的指针扫描字符串,同时更新散列表。 如果该字符已经在hashmap中,则将左指针移到最后找到的同一个字符的右侧。 请注意,这两个指针只能向前移动。

  • 代码

    package String;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;/*** @Author OovEver* @Date 2017/12/8 23:47*/public class LeetCode3 {  public static int lengthOfLongestSubstring(String s) {      if (s.length() == 0) {          return 0;      }      Map<Character, Integer> map = new HashMap<>();      int max = 0;//        upper记录      for(int i=0,upper=0;i<s.length();i++) {          if (map.containsKey(s.charAt(i))) {              upper = Math.max(upper, map.get(s.charAt(i)) + 1);          }          map.put(s.charAt(i), i);          max = Math.max(max, i - upper + 1);      }      return max;  }  public static void main(String[] args) {      String s = "abba";      System.out.println(lengthOfLongestSubstring(s));  }}
阅读全文
0 0
原创粉丝点击