diff --git a/README.md b/README.md index c4a2494a..f154a5b2 100644 --- a/README.md +++ b/README.md @@ -461,3 +461,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). |---------------------------------------------------|---------------------------------------------------------------------------------------|--------------------------------------------------------------------------| | 2. Add Two Numbers | [Link](https://leetcode.com/problems/add-two-numbers/) | [Link](./lib/medium/2_add_two_numbers.rb) | | 3. Longest Substring Without Repeating Characters | [Link](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Link](./lib/medium/3_longest_substring_without_repeating_characters.rb) | +| 5. Longest Palindromic Substring | [Link](https://leetcode.com/problems/longest-palindromic-substring/) | [Link](./lib/medium/5_longest_palindromic_substring.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 596803c4..cc6f51cf 100644 --- a/leetcode-ruby.gemspec +++ b/leetcode-ruby.gemspec @@ -5,7 +5,7 @@ require 'English' ::Gem::Specification.new do |s| s.required_ruby_version = '>= 3.0' s.name = 'leetcode-ruby' - s.version = '5.9.5' + s.version = '5.9.6' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE] s.executable = 'leetcode-ruby' diff --git a/lib/medium/5_longest_palindromic_substring.rb b/lib/medium/5_longest_palindromic_substring.rb new file mode 100644 index 00000000..b2dd75a9 --- /dev/null +++ b/lib/medium/5_longest_palindromic_substring.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/longest-palindromic-substring/ +# @param {String} s +# @return {String} +def longest_palindrome5(s) + result = '' + + (0...s.length).each do |i| + str1 = find_longest_palindrome(i, i, s) + str2 = find_longest_palindrome(i, i + 1, s) + + result = [result, str1, str2].max_by(&:size) + end + + result +end + +# @param {Integer} l +# @param {Integer} r +# @param {String} s +# @return {String} +def find_longest_palindrome(l, r, s) + while l >= 0 && r < s.size && s[l] == s[r] + l -= 1 + r += 1 + end + + s[(l + 1)..(r - 1)] +end diff --git a/test/medium/test_5_longest_palindromic_substring.rb b/test/medium/test_5_longest_palindromic_substring.rb new file mode 100644 index 00000000..ec793ffa --- /dev/null +++ b/test/medium/test_5_longest_palindromic_substring.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/5_longest_palindromic_substring' +require 'minitest/autorun' + +class LongestPalindromicSubstringTest < ::Minitest::Test + def test_default + assert_equal('bab', longest_palindrome5('babad')) + assert_equal('bb', longest_palindrome5('cbbd')) + end +end