-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.ts
More file actions
68 lines (53 loc) · 1.52 KB
/
4.ts
File metadata and controls
68 lines (53 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const convertString = (palindrome: string) => {
const palindromeLength = palindrome.length
const strArr = new Array<string>(palindromeLength).fill('')
const isOddOrNot = isOdd(palindromeLength)
const middleOfArr = Math.floor(palindromeLength / 2)
let tempString = palindrome
for (let index = 0; index < palindromeLength / 2; index++) {
if (isOddOrNot && index === middleOfArr) {
strArr[index] = tempString[0]
break
}
strArr[index] = tempString[0]
strArr[palindromeLength - 1 - index] = tempString[1]
tempString = tempString.slice(2)
}
return strArr.filter(Boolean).reduce((prev, current) => {
return `${prev}${current}`
}, '')
}
const isOdd = (num: number) => !isEven(num)
const isEven = (num: number) => num % 2 === 0
export const longestPalindrome = (s: string): string => {
const pureStr = s.replace(' ', '').toLowerCase()
const pureStrLength = pureStr.length
let start = 0
let end = pureStrLength - 1
let palindrome = ''
let count = 0
while (count < pureStrLength) {
const startLetter = pureStr[start]
const endLetter = pureStr[end]
if (start >= end && !isEven(pureStrLength)) {
palindrome += startLetter
break
}
if (start >= end && isEven(pureStrLength)) {
break
}
if (startLetter === endLetter) {
palindrome += startLetter + endLetter
start++
end--
count++
continue
}
palindrome = ''
count++
start++
end--
}
palindrome = convertString(palindrome)
return palindrome
}