๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/LeetCode

[LeetCode] 003. Longest Substring Without Repeating Characters JAVA

by Bhinney 2022. 12. 16.
 

Longest Substring Without Repeating Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


๐Ÿ“Œ ๋ฌธ์ œ

Given a string s, find the length of the longest substring without repeating characters.

๐Ÿ“Œ ๋ฐฉ๋ฒ•

  • ์ปฌ๋ ‰์…˜์„ ์ด์šฉํ•˜์—ฌ ํ’€์ด
  • ๊ทธ ์ค‘์—์„œ Set์˜ HashSet์„ ์ด์šฉํ•˜์—ฌ ํ’€์ด

1๏ธโƒฃ ์ตœ๋Œ“๊ฐ’ max ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”

2๏ธโƒฃ HashSet์„ ์ด์šฉํ•˜์—ฌ ํ’€์ด

3๏ธโƒฃ ์‹œ์ž‘ ๋ณ€์ˆ˜๊ณผ ๋๋‚˜๋Š”  ๋ณ€์ˆ˜ ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”

4๏ธโƒฃ while ๋ฌธ์œผ๋กœ ํ’€์ด (O(n)์˜ ๋ณต์žก๋„๋กœ ํ’€์ด)

5๏ธโƒฃ ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜์”ฉ ์ฐจ๋ก€๋กœ ๋น„๊ต

6๏ธโƒฃ ์กฐ๊ฑด๋ฌธ์„ ์ด์šฉํ•˜์—ฌ set์— ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด set์— ๋„ฃ์–ด์ฃผ๊ณ  end ๊ฐ’ ++

7๏ธโƒฃ ๋ - ์‹œ์ž‘ ๋บ€ ๊ฐ’์„ ๊ตฌํ•ด ๊ทธ ์ค‘์—์„œ max ๊ฐ’์„ ๊ตฌํ•˜๊ธฐ

8๏ธโƒฃ ๋งŒ์•ฝ set์— ์กด์žฌํ•˜๋ฉด ์‹œ์ž‘์ ์˜ ๋ฌธ์ž ์ง€์šฐ๊ธฐ

 

import java.util.HashSet;

class Solution {
    public int lengthOfLongestSubstring(String s) {
    
        HashSet<Character> set = new HashSet<>();
        
        /*  ๋ฐ˜ํ™˜ํ•  ์ตœ๋Œ€ ๊ฐ’ ์ดˆ๊ธฐํ™” */
        int max = 0;
        int start = 0;
        int end = 0;
        
        while (end < s.length()) {
            if (start > end) {
                break;
            }
            if (!set.contains(s.charAt(end))) {
                set.add(s.charAt(end++));
                max = Math.max(max, end - start);
                continue;
            }
            set.remove(s.charAt(start++));
        }
        
        return max;
    }
}

 

'์•Œ๊ณ ๋ฆฌ์ฆ˜ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode]006. Zigzag Conversion JAVA  (0) 2022.12.21
[LeetCode]007. Reverse Integer JAVA  (0) 2022.12.19
[LeetCode]005. Longest Palindromic Substring JAVA  (0) 2022.12.19
[LeetCode] 002. Add Two Numbers JAVA  (0) 2022.12.16
[LeetCode] 001. Two Sum JAVA  (0) 2022.12.15

๋Œ“๊ธ€