Skip to content

Commit eecebfe

Browse files
authored
Merge pull request #162 from jsca-kwok/jk-palindrome
Add almost palindrome algorithm
2 parents f5c87a4 + a0952eb commit eecebfe

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
* [Sort Squares Of An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/sort_squares_of_an_array.rb)
3737
* [Sorted Arrays Intersection](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/sorted_arrays_intersection.rb)
3838
* Strings
39+
* [Almost Palindrome Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/almost_palindrome_checker.rb)
3940
* [Anagram Checker](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/anagram_checker.rb)
4041
* [Jewels And Stones](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/jewels_and_stones.rb)
4142
* [Palindrome](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/strings/palindrome.rb)
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Challenge name: Almost Palindrome
2+
#
3+
# Given a string s, return true if the s can be palindrome after deleting at most one character from it.
4+
#
5+
# Example 1:
6+
# Input: s = "aba"
7+
# Output: true
8+
#
9+
# Example 2:
10+
# Input: s = "abca"
11+
# Output: true
12+
# Explanation: You could delete the character 'c'.
13+
#
14+
# Example 3:
15+
# Input: s = "abc"
16+
# Output: false
17+
#
18+
# Constraints:
19+
# 1 <= s.length <= 105
20+
# s consists of lowercase English letters.
21+
22+
#
23+
# Approach 1: Two Pointers
24+
#
25+
26+
# Complexity Analysis:
27+
#
28+
# Time Complexity: O(n)
29+
# Space Complexity: O(1)
30+
31+
32+
def almost_palindrome_checker(string)
33+
p1 = 0
34+
p2 = string.length - 1
35+
array = string.split('')
36+
37+
while p1 < p2
38+
if array[p1] != array[p2]
39+
return palindrome_checker(array, p1, p2 - 1) || palindrome_checker(array, p1 + 1, p2)
40+
end
41+
p1 += 1
42+
p2 -= 1
43+
end
44+
45+
true
46+
end
47+
48+
def palindrome_checker(array, p1, p2)
49+
while p1 < p2
50+
if array[p1] != array[p2]
51+
return false
52+
end
53+
p1 += 1
54+
p2 -= 1
55+
end
56+
57+
true
58+
end
59+
60+
puts almost_palindrome_checker('aba')
61+
# => true
62+
63+
puts almost_palindrome_checker('abca')
64+
# => true
65+
66+
puts almost_palindrome_checker('abc')
67+
# => false

0 commit comments

Comments
 (0)