[Swift] LongestPassword 문제 풀이 [Codility - Exercise 1. 2015 Contest]
💬 문제
https://app.codility.com/programmers/trainings/1/longest_password/
LongestPassword coding task - Practice Coding - Codility
Given a string containing words, find the longest word that satisfies specific conditions.
app.codility.com
💬 Idea
- 코딜리티는 풀이 언어로 Swift4를 지원하는데, Swift4에서는 Character에서 isLetter, isNumber를 사용하는 것이 안되는 것 같다..
- 찾아보니 Character에서 Unicode 속성을 테스트 할 수 있는 속성들은 Swift5에서 추가되었네요 ~!
- https://jercy.tistory.com/10
- 그래서 정규표현식을 사용하여 문제를 풀이했다.
- “문자가 짝수개일 것” 조건을 판별해주기 위해 숫자인 문자들을 “”으로 치환해주었다. 치환 후에는 문자만 남게 되기 때문에 치환 후 남은 문자의 개수를 세어 판별했다.
💬 풀이
public func solution(_ S : inout String) -> Int {
let s = S.components(separatedBy: .whitespaces).filter({ $0.count % 2 == 1 })
var longestSCount = -1
for i in s {
if checkIsValidString(i) {
if longestSCount < i.count {
longestSCount = i.count
}
}
}
return longestSCount
}
public func checkIsValidString(_ S: String) -> Bool {
// 1. 숫자와 영문자만 포함할 것
let regexPattern = "^[0-9a-zA-Z]*$"
guard let _ = S.range(of: regexPattern, options: .regularExpression) else { return false }
// 2. 문자가 짝수개일 것
if S.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression).count % 2 != 0 { return false }
return true
}
https://app.codility.com/demo/results/trainingH74JG3-CYY/
Test results - Codility
You would like to set a password for a bank account. However, there are three restrictions on the format of the password: it has to contain only alphanumerical characters (a−z, A−Z, 0−9); there should be an even number of letters; there should be an
app.codility.com
GitHub - hwangJi-dev/swiftAlgorithm: Algorithm Practice with Swift
Algorithm Practice with Swift. Contribute to hwangJi-dev/swiftAlgorithm development by creating an account on GitHub.
github.com