|
| 1 | +package valid_palindrome |
| 2 | + |
| 3 | +import ( |
| 4 | + "regexp" |
| 5 | + "strings" |
| 6 | +) |
| 7 | + |
| 8 | +/* |
| 9 | + 1. 문제 |
| 10 | + 회문. 주어진 문자열 s 를 모두 소문자로 바꾸고, alphanumeric 이 아닌 문자를 제외할 때, |
| 11 | + 앞으로 읽으나 뒤로 읽으나 같은 문자열인지 체크 (회문) |
| 12 | +
|
| 13 | + 2. 풀이 |
| 14 | + - 주어진 문자열 s 에서 alphanumeric character 만 남기고 제거. |
| 15 | + - 모두 소문자로 변환 |
| 16 | + - 앞, 뒤로 인덱스 위치를 기록하는 cursor 를 정의 |
| 17 | + 커서 둘을 앞, 뒤로 전진하며 같지않은 문자가 나오면 false 를 반환, 그렇지 않고 회문이면 true 를 반환. |
| 18 | +
|
| 19 | +3. 분석 |
| 20 | + - 시간 복잡도: O(N) |
| 21 | + regex.ReplaceAllString(): O(n) |
| 22 | + 모든 문자열을 돌며 regex 검사 후 대체 |
| 23 | + strings.ToLower(str): O(n) |
| 24 | + 모든 문자열을 돌며 소문자로 변환 |
| 25 | + palindrome 문자열 체크 loop |
| 26 | + 앞 커서 < 뒤 커서 의 조건으로 O(n/2) ---> O(n) |
| 27 | + - 공간 복잡도: O(1) |
| 28 | + 새로운 저장공간은 없으며 주어진 문자열 s 하나뿐 |
| 29 | +*/ |
| 30 | +var nonAlphanumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]+`) |
| 31 | + |
| 32 | +func isPalindrome(s string) bool { |
| 33 | + s = nonAlphanumericRegex.ReplaceAllString(s, "") |
| 34 | + s = strings.ToLower(s) |
| 35 | + // 앞, 뒤 커서 |
| 36 | + front, rear := 0, len(s)-1 |
| 37 | + |
| 38 | + for front < rear { |
| 39 | + frontCh := s[front] |
| 40 | + readCh := s[rear] |
| 41 | + |
| 42 | + // 선택한 두 문자가 다르면 실패! |
| 43 | + if frontCh != readCh { |
| 44 | + return false |
| 45 | + } |
| 46 | + |
| 47 | + front++ |
| 48 | + rear-- |
| 49 | + } |
| 50 | + |
| 51 | + return true |
| 52 | +} |
| 53 | + |
| 54 | +/* |
| 55 | +1. 개선점 |
| 56 | + - regex 오버헤드 제거 |
| 57 | +*/ |
| 58 | +func isPalindrome_Optimized(s string) bool { |
| 59 | + front, rear := 0, len(s)-1 |
| 60 | + |
| 61 | + for front < rear { |
| 62 | + for front < rear && !isAlphanumeric(s[front]) { |
| 63 | + front++ |
| 64 | + } |
| 65 | + |
| 66 | + for front < rear && !isAlphanumeric(s[rear]) { |
| 67 | + rear-- |
| 68 | + } |
| 69 | + |
| 70 | + if toLower(s[front]) != toLower(s[rear]) { |
| 71 | + return false |
| 72 | + } |
| 73 | + |
| 74 | + front++ |
| 75 | + rear-- |
| 76 | + } |
| 77 | + |
| 78 | + return true |
| 79 | +} |
| 80 | + |
| 81 | +func isAlphanumeric(ch byte) bool { |
| 82 | + return (ch >= 'a' && ch <= 'z') || |
| 83 | + (ch >= 'A' && ch <= 'Z') || |
| 84 | + (ch >= '0' && ch <= '9') |
| 85 | +} |
| 86 | + |
| 87 | +func toLower(ch byte) byte { |
| 88 | + if ch >= 'A' && ch <= 'Z' { |
| 89 | + return ch + 32 |
| 90 | + } |
| 91 | + return ch |
| 92 | +} |
0 commit comments