Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created December 18, 2019 12:47
Show Gist options
  • Save spurscho/ea2eb3e9723d7a7244c97765e37503b1 to your computer and use it in GitHub Desktop.
Save spurscho/ea2eb3e9723d7a7244c97765e37503b1 to your computer and use it in GitHub Desktop.
5. Longest Palindromic Substring (Time limit exceeded)
class Solution {
func longestPalindrome(_ s: String) -> String {
// x 문자와 같은 문자가 나올때까지 for문, tempStr값에 계속 추가
// x와 같은 문자가 나왔을시 그 문자를 tempStr값에 포함한 후 tempStr.count가 짝수인지, 홀수인지 확인.
// tempStr.count가 result.count보다 크면 진행, 아니면 continue
// 짝수일경우, tempStr를 절반으로 나누고 절반을 역방향으로 수정해준다. 그 후 양쪽의 데이터가 같은지 확인하고, 같으면 result에 추가.
// 홀수일경우, tempStr의 중간 인덱스를 제외한 나머지 절반을 역방향으로 수정한다. 그 후 양쪽의 데이터가 같은지 확인하고, 같으면 result에 추가.
if s.count < 1 || s.count > 1000 {
return ""
}
let arr = Array(s)
var refIndx: Int = 0
var tempStr: String = ""
var result: String = "\(arr[0])"
var x = 0
while x < arr.count {
tempStr = "\(arr[x])"
for i in x+1 ..< arr.count {
tempStr += "\(arr[i])"
if arr[x] == arr[i] {
if tempStr.count < result.count {
continue
}
if tempStr.count % 2 == 0 { // 짝수
let aa = tempStr.startIndex..<tempStr.index(tempStr.startIndex, offsetBy: tempStr.count/2)
let bb = tempStr.index(tempStr.startIndex, offsetBy: tempStr.count/2)..<tempStr.endIndex
if isSummetry(String(tempStr[aa]),String(tempStr[bb])) == true { // 대칭
result = tempStr
}
} else { // 홀수
let aa = tempStr.startIndex..<tempStr.index(tempStr.startIndex, offsetBy: tempStr.count/2)
let bb = tempStr.index(tempStr.startIndex, offsetBy: (tempStr.count/2 + 1))..<tempStr.endIndex
if isSummetry(String(tempStr[aa]),String(tempStr[bb])) == true { // 대칭
result = tempStr
}
}
}
}
x += 1
}
return result
}
func isSummetry(_ str1: String, _ str2: String) -> Bool {
if str1 == String(str2.reversed()) {
return true
} else {
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment