File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .HashSet ;
2+ import java .util .Set ;
3+
4+ class SolutionLongestSubstring {
5+
6+ public int lengthOfLongestSubstring (String s ) {
7+ // 반복되는 문자열 중 가장 긴 문자열의 길이를 반환해라
8+
9+ // s.length = 0 또는 1이면 return s.length()
10+ // lt = 0, rt = 1
11+ // s[lt] != s[rt] 이면 SubString 여부를 검사하고 True면 rt++, count++
12+ // s[lt] == s[rt] 이면 쌓인 카운트 정답에 적용하고 lt++, rt=lt+1, count 초기화
13+ // rt가 끝에 도달하면 그때까지 쌓인 정답 반환
14+
15+ // TC: O(N*M), 전체 문자열 길이 N * 부분 문자열 길이 M
16+ // SC: O(M), 부분 문자열 생성 공간
17+
18+ if (s .length () <= 1 ) {
19+ return s .length ();
20+ }
21+
22+ int lt = 0 ;
23+ int rt = lt + 1 ;
24+ int answer = 0 ;
25+ int count = 0 ;
26+ while (rt <= s .length ()) {
27+ while (rt <= s .length () && isSubstring (s .substring (lt , rt ))) {
28+ count ++;
29+ rt ++;
30+ }
31+ answer = Math .max (answer , count );
32+
33+ lt ++;
34+ rt = lt + 1 ;
35+ count = 0 ;
36+ }
37+ return answer ;
38+ }
39+
40+ // TC: O(M), 부분 문자열 str에 중복이 없는 경우 str의 길이
41+ // SC: O(M), 부분 문자열 str의 중복이 없는 경우 str의 길이
42+ private boolean isSubstring (String str ) {
43+ Set <Character > set = new HashSet <>();
44+ set .add (str .charAt (0 )); // 첫번째 문자는 바로 add
45+ // 두번째 문자부터 중복 검사 대상
46+ for (int i = 1 ; i < str .length (); i ++) {
47+ // 중복 문자가 있거나, 공백이면 바로 false 리턴
48+ if (!set .add (str .charAt (i )) || str .charAt (i ) == ' ' ) {
49+ return false ;
50+ }
51+ }
52+
53+ return true ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments