欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

II Hash Table: 2. Longest Substring Without Repeating Characters,longestrepeating

来源: javaer 分享于  点击 3435 次 点评:248

II Hash Table: 2. Longest Substring Without Repeating Characters,longestrepeating


3. Longest Substring Without Repeating Characters
given: a string, find the length of the longest substring without repeating characters. 
       e.g. 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.


one way to use HashSet to track the longest substring without repeating characters so far, use a fast pointer
j to see if character j is in the hash set or not, if not, great, add it to the has set, move j forward and update
the max length, otherwise, delete from the head by using a slow pointer i util we can put character j to the hash set


public class Solution{
    public int lengthOfLongestSubstring(String s){
         int i = 0, j = 0, max = 0;
         Set<Character> set = new HashSet<>();
         while (j<s.length()){
             if(!set.contains(s.charAt(j))){
                 set.add(s.charAt(j++));
                 max=Math.max(max, set.size());
              }else{
                 set.remove(s.charAt(i++));
              }
          }
          return max;
      }
}

相关文章

    暂无相关文章

用户点评