Algorithm/LeetCode
LeetCode 3.Longest Substring Without Repeating Characters
hhsaebom
2020. 12. 2. 16:55
문제요약: 문자열(input)이 주어졌을때, 반복되는 문자(Character)없는 가장 긴 문자열의 길이를 반환 하시오.
예: input => abcabcbb 정답: 3
input => bbbbb 정답: 1
input => pwwkew 정답: 3
문제접근: 문자열을 처음부터 반복을하면서 똑같은 문자열을 만나기 전까지 루프를 돈다. 만약 반복된 문자열을 만나면 다음 루프로 넘어가고, 이전에 가장 긴 문자열과 비교해서 가장 긴 길이를 체크한다.
구현코드: 언어는 java 사용
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String input) {
// 빈 문자열이면 그냥 0을 반환
if (input.equals("")) return 0;
// 가장긴 문자열을 저장해놀 변수
int maxLength = 0;
// 문자열을 처음부터 반복해서 중복없는 가장 긴 문자열을 찾는다.
for (int i = 0 ; i < input.length() ; i++) {
char element = input.charAt(i);
// 현재 루프에서 중복없는 문자열을 만들 변수
String result = element + "";
// 중복된 문자열을 체크할 Set 객체 생성
Set<Character> elementSet = new HashSet<>();
elementSet.add(element);
// 현재문자열 다음 문자열부터 중복체크를 하기위해 이중루프 사용
for (int j = i + 1; j < input.length() ; j++) {
char nextElement = input.charAt(j);
// set에 문자열이 있다면 루프 종료
if (elementSet.contains(nextElement)) {
break;
// 없다면 문자열을 더하고 set에도 넣는다.
} else {
elementSet.add(nextElement);
result = result + nextElement;
}
}
// 문자열길이가 더 길면 변수값 변경
if (result.length() > maxLength) {
maxLength = result.length();
}
}
return maxLength;
}
}