-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18_palindrome.rb
More file actions
58 lines (44 loc) · 1.18 KB
/
18_palindrome.rb
File metadata and controls
58 lines (44 loc) · 1.18 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
# Palindrome Substrings
# Given a string, write a method to count the palindromic substrings.
# Example 1
# Input: "abc"
# Output: 3
# Explanation: Three palindromic strings: "a", "b", "c".
# Example 2
# Input: "aaa"
# Output: 6
# Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
# solution for unique palindromic strings
def palindrome_counter(word)
substrings_array = []
word_length = word.length - 1
0.upto(word_length) do |n|
word_length.times do |m|
substring = word.slice(n..m-1)
if substring == substring.reverse
substrings_array << substring
end
end
end
substrings_array.uniq.count
end
puts palindrome_counter('racecar')
puts palindrome_counter('aaa')
puts palindrome_counter('abc')
# solution for non-unique palindromic strings
# def palindrome_counter(word)
# count = 0
# word_length = word.length - 1
# 0.upto(word_length) do |n|
# word_length.times do |m|
# substring = word.slice(n..m-1)
# if substring == substring.reverse
# count += 1
# end
# end
# end
# count
# end
# puts palindrome_counter('racecar')
# puts palindrome_counter('aaa')
# puts palindrome_counter('abc')