티스토리 뷰

문제보러가기

 

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

우선 이문제는 중복되지 않는 부분 문자열의 가장 긴 길이를 찾는 문제였다. 투 포인터를 사용해서 해결하였다.

 

 

 

 

문제풀이

-빈 문자열이나 한 글자인 문자열은 미리 체크를 하여 빼준다.

-첫 글자를 부분 문자를 확인하는 str변수에 넣어준 후 반복문을 통해 탐색해준다.

-end가 주어진 문자열인 s길이를 벗어날 경우 종료.

 

-start 인텍스 ++조건

: 현재 비교하는 부분 문자열에 end인덱스에 해당하는 알파벳이 있을경우

 

-end 인덱스 ++조건

: 현재 비교하는 부분문자열에 end인덱스에 해당하는 알파벳이 없을 경우

 

-각각 조건마다 max값을 현재 str길이와 비교해서 갱신해준다.

 

 

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start=0;
	int end=1;
	int max = Integer.MIN_VALUE;
        
        if(s.length()==0)
            return 0;
        if(s.length()==1)
            return 1;
	String str=s.substring(0,1);
	while(true) {
		if(end>=s.length()) break;
		if(str.contains(s.charAt(end)+"")) {
			start++;
			max = Math.max(max,str.length() );
			str = s.substring(start, end);
		}else {
			str += s.charAt(end);
			max = Math.max(max,str.length() );
			end++;
		}
			
	}

		return max;
    }
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함