-
[코딩인터뷰완전분석] 1.1_중복이 없는가_풀이알고리즘 2021. 8. 24. 00:06
Q. 문자열이 주어졌을 때, 이 문자열에 같은 문자가 중복되어 등장하는지 확인하는 알고리즘을 작성하라
[체크] 문제를 풀기 전 ASCII 코드인지, 유니 코드인지 확인하자. 이 가정이 없다면, 배열의 크기를 늘려야한다.
boolean isUnique (String str) { // ASCII 코드라 가정 1byte -> 2의8승, // 1비트는 값 표현에 쓰이지 않으므로 2의7승 최대 128개의 문자열이 들어온다. if (str.length() > 128) return false; boolean charSet = new boolean[128]; // charAt 함수를 통해 아스키 코드 값을 가져온 후 해당 아스키 코드값을 인덱스값으로 설정한다. // 그 후 해당 인덱스의 값을 true 로 설정. // 중복되는 문자일 경우 해당 배열방에 true 가 존재할 것이다. for (int i=0; i<str.length(); i++) { int val = str.charAt(i); if (charSet[val]) { return false; } charSet[val] = true; } return true; }
'알고리즘' 카테고리의 다른 글
[코딩인터뷰완전분석] 1.2_순열확인_풀이 (0) 2021.08.24 [leetcode] Height Checker (0) 2021.08.24 알고리즘 학습법 (0) 2021.08.21 [LeetCode] Palindrome Number (0) 2021.06.22 [LeetCode] Median of Two Sorted Arrays (0) 2021.06.17