TheAlgorithms-Ruby/data_structures/arrays/strings/almost_palindrome_checker.rb

68 lines
1.1 KiB
Ruby
Raw Normal View History

2021-06-29 23:00:08 +02:00
# Challenge name: Almost Palindrome
#
# Given a string s, return true if the s can be palindrome after deleting at most one character from it.
#
# Example 1:
# Input: s = "aba"
# Output: true
#
# Example 2:
# Input: s = "abca"
# Output: true
# Explanation: You could delete the character 'c'.
#
# Example 3:
# Input: s = "abc"
# Output: false
#
# Constraints:
# 1 <= s.length <= 105
# s consists of lowercase English letters.
2021-07-02 21:52:55 +02:00
#
2021-06-29 23:00:08 +02:00
# Approach 1: Two Pointers
2021-07-02 21:52:55 +02:00
#
# Complexity Analysis:
#
2021-06-29 23:00:08 +02:00
# Time Complexity: O(n)
2021-07-02 21:52:55 +02:00
# Space Complexity: O(1)
2021-06-29 23:00:08 +02:00
def almost_palindrome_checker(string)
p1 = 0
p2 = string.length - 1
2021-07-02 21:45:20 +02:00
array = string.split('')
2021-06-29 23:00:08 +02:00
while p1 < p2
2021-07-02 21:45:20 +02:00
if array[p1] != array[p2]
return palindrome_checker(array, p1, p2 - 1) || palindrome_checker(array, p1 + 1, p2)
2021-06-29 23:00:08 +02:00
end
p1 += 1
p2 -= 1
end
true
end
2021-07-02 21:45:20 +02:00
def palindrome_checker(array, p1, p2)
2021-06-29 23:00:08 +02:00
while p1 < p2
2021-07-02 21:45:20 +02:00
if array[p1] != array[p2]
2021-06-29 23:00:08 +02:00
return false
end
p1 += 1
p2 -= 1
end
true
end
puts almost_palindrome_checker('aba')
# => true
puts almost_palindrome_checker('abca')
# => true
puts almost_palindrome_checker('abc')
2021-07-02 21:52:55 +02:00
# => false