hwangnk1004 / leetcode_study

0 stars 0 forks source link

3. Longest Substring Without Repeating Characters #2

Open hwangnk1004 opened 2 years ago

hwangnk1004 commented 2 years ago

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

hwangnk1004 commented 2 years ago
class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();

        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            if (!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), i);
            } else {
                i = map.get(s.charAt(i));
                map.clear();
            }

            if (result < map.size()) {
                result = map.size();
            }
        }
        return result;
    }
}

스크린샷 2022-01-21 오후 7 44 06

hwangnk1004 commented 2 years ago

다른 사람 풀이

    public int lengthOfLongestSubstring(String s) {
        // 한 글자씩만 나와야한다. ex, abca 는 a 가 두번나오므로 안된다.
        int maxLength = 0;
        int i=0, j=0;
        int length = s.length();
        HashSet<Character> stringSet = new HashSet<>();

        while (j < length) {
            if(i > j) break;
            if (!stringSet.contains(s.charAt(j))){
                stringSet.add(s.charAt(j++));
                maxLength = Math.max(maxLength, j - i);
                continue;
            }
            stringSet.remove(s.charAt(i++));

        }

        return maxLength;
    }
}
스크린샷 2022-01-23 오후 2 27 47
hwangnk1004 commented 2 years ago

재 풀이

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

image