# LeetCode 勉強会
だいたい毎週金曜日20:00〜21:00に雑談部屋でやっています。
不定期で休みのことがあります。
Easyレベルしかやっていないゆるゆるの会です。
参加する人はできれば問題にはチャレンジしてください。書いたコードを公開するかは自由です。
## 次回は未定?
引き続きこれ↓をやる予定
https://leetcode.com/problems/longest-common-prefix/description/
## 2024/5/10
https://leetcode.com/problems/longest-common-prefix/description/
```ruby!
# 考え中...
def longest_common_prefix(strs)
prefix = strs[0]
strs.shift
strs.all? do |v|
v.start_with?(prefix)
end
end
```
- https://docs.ruby-lang.org/ja/latest/method/String/i/start_with=3f.html
## 2024/4/26
https://leetcode.com/problems/palindrome-number/
palindrome: 回文(逆から読んでも同じになる語句)
```ruby!
# @param {Integer} x
# @return {Boolean}
def is_palindrome(x)
x.to_s.reverse == x.to_s
end
```
https://leetcode.com/problems/roman-to-integer/description/
↓人間の回答
```ruby!
# @param {String} s
# @return {Integer}
def roman_to_int(s)
s.gsub!(/IV/, 'あ')
s.gsub!(/IX/, 'い')
s.gsub!(/XL/, 'う')
s.gsub!(/XC/, 'え')
s.gsub!(/CD/, 'お')
s.gsub!(/CM/, 'か')
hash = {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000,
'あ' => 4,
'い' => 9,
'う' => 40,
'え' => 90,
'お' => 400,
'か' => 900
}
array = s.split('').map do |l|
hash[l]
end
array.sum
end
```
↓ChatGPT の回答
```ruby!
def roman_to_int(s)
roman_values = {
'I' => 1,
'V' => 5,
'X' => 10,
'L' => 50,
'C' => 100,
'D' => 500,
'M' => 1000
}
total = 0
prev_value = 0
s.chars.reverse_each do |char|
value = roman_values[char]
if value < prev_value
total -= value
else
total += value
end
prev_value = value
end
total
end
# Test cases
puts roman_to_int("III") # Output: 3
puts roman_to_int("LVIII") # Output: 58
puts roman_to_int("MCMXCIV") # Output: 1994
```
## 2024/4/19
https://leetcode.com/problems/two-sum/
```ruby!
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
num_indices = {}
nums.each_with_index do |n, i|
complement = target - n
if num_indices.key?(complement)
return [num_indices[complement], i]
end
num_indices[n] = i
end
end
```