Leetcode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:java手机游戏免费下载 编辑:程序博客网 时间:2024/05/15 15:05

O(n)

public class Solution {    public int lengthOfLongestSubstring(String s) {        HashSet<Character> hs = new HashSet<Character>();        int max = 0, fast = 0, slow = 0;        while (fast < s.length()) {            if (!hs.add(s.charAt(fast))) {                hs.remove(s.charAt(slow));                slow++;            }            else {                // maintain the maximum length                max = Math.max(max, fast-slow+1);                fast++;            }        }        return max;    }}

O(n^2)

// using a hashset to save the sunstring starting from 0, 1, ..., n // keep recording the length for each substring// if max < current length, set max = current lengthpublic class Solution {    public int lengthOfLongestSubstring(String s) {        HashSet<Character> hs = new HashSet<Character>();        int max = 0;                // check the length for substring starts from i        for (int i=0; i<s.length(); i++) {            // tmp to save the current substring's length            int tmp = 0, j = i;            while (j < s.length()) {                // found a duplicate character                if (!hs.add(s.charAt(j)))                    break;                tmp++;                j++;            }            // clear the hashset after each iteration            hs.clear();            // save the maximum length            max = Math.max(tmp, max);        }                return max;    }}


0 0
原创粉丝点击