Skip to content

Commit 4948512

Browse files
committed
125. Valid Palindrome
1 parent 6d8eb57 commit 4948512

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
| 113 | Path Sum II | [Ruby](./algorithms/ruby/0113-path-sum-ii.rb) | Medium |
6767
| 121 | Best Time to Buy and Sell Stock | [Ruby](./algorithms/ruby/0121-best-time-to-buy-and-sell-stock.rb) | Easy |
6868
| 122 | Best Time to Buy and Sell Stock II | [Ruby](./algorithms/ruby/0122-best-time-to-buy-and-sell-stock-ii.rb) | Medium |
69+
| 125 | Valid Palindrome | [Ruby](./algorithms/ruby/0125-valid-palindrome.rb) | Easy |
6970
| 129 | Sum Root to Leaf Numbers | [Ruby](./algorithms/ruby/0129-sum-root-to-leaf-numbers.rb) | Medium |
7071
| 133 | Clone Graph | [Ruby](./algorithms/ruby/0133-clone-graph.rb) | Medium |
7172
| 134 | Gas Station | [Ruby](./algorithms/ruby/0134-gas-station.rb) | Easy |
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# frozen_string_literal: true
2+
3+
# 125. Valid Palindrome
4+
# https://leetcode.com/problems/valid-palindrome
5+
# Easy
6+
7+
=begin
8+
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
9+
10+
Given a string s, return true if it is a palindrome, or false otherwise.
11+
12+
Example 1:
13+
Input: s = "A man, a plan, a canal: Panama"
14+
Output: true
15+
Explanation: "amanaplanacanalpanama" is a palindrome.
16+
17+
Example 2:
18+
Input: s = "race a car"
19+
Output: false
20+
Explanation: "raceacar" is not a palindrome.
21+
22+
Example 3:
23+
Input: s = " "
24+
Output: true
25+
Explanation: s is an empty string "" after removing non-alphanumeric characters.
26+
Since an empty string reads the same forward and backward, it is a palindrome.
27+
28+
Constraints:
29+
1 <= s.length <= 2 * 105
30+
s consists only of printable ASCII characters.
31+
=end
32+
33+
# @param {String} s
34+
# @return {Boolean}
35+
def is_palindrome(s)
36+
filtered_s = s.gsub(/[^a-bA-Z0-9]/i, "").downcase
37+
left, right = 0, filtered_s.size - 1
38+
39+
while left < right
40+
return false if filtered_s[left] != filtered_s[right]
41+
left += 1
42+
right -= 1
43+
end
44+
45+
true
46+
end
47+
48+
# **************** #
49+
# TEST #
50+
# **************** #
51+
52+
require "test/unit"
53+
class Test_is_palindrome < Test::Unit::TestCase
54+
def test_
55+
assert_equal true, is_palindrome("A man, a plan, a canal: Panama")
56+
assert_equal false, is_palindrome("race a car")
57+
assert_equal true, is_palindrome("")
58+
end
59+
end

0 commit comments

Comments
 (0)