您的位置:首页 > 其它

II Hash Table: 2. Longest Substring Without Repeating Characters

2016-01-03 00:21 316 查看
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;

      }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: