LoginSignup
2
0

More than 3 years have passed since last update.

Ruby で解く AtCoder ABC110 C 文字列操作

Posted at

はじめに

AtCoder Problems の Recommendation を利用して、過去の問題を解いています。
AtCoder さん、AtCoder Problems さん、ありがとうございます。

今回のお題

AtCoder Beginner Contest C - String Transformation
Difficulty: 946

今回のテーマ、文字列操作

異なる英小文字ですので、逆に考えますと重複を考慮するということで、重複した文字列と言えばハッシュ
コインの裏の裏が表であるように、ハッシュの逆の逆を調べます。

Ruby

ruby.rb
s = gets.chomp.chars
t = gets.chomp.chars
h = {}
g = {}
s.size.times do |i|
  if h[s[i]]
    if h[s[i]].count(t[i]) == 0
      h[s[i]] << t[i]
    end
  else
    h[s[i]] = [t[i]]
  end
  if g[t[i]]
    if g[t[i]].count(s[i]) == 0
      g[t[i]] << s[i]
    end
  else
    g[t[i]] = [s[i]]
  end
end
puts h.flatten(-1) == g.invert.flatten(-1) ? 'Yes' : 'No'
hash.rb
h = {}
g = {}
s.size.times do |i|
  if h[s[i]]
    if h[s[i]].count(t[i]) == 0
      h[s[i]] << t[i]
    end
  else
    h[s[i]] = [t[i]]
  end
  if g[t[i]]
    if g[t[i]].count(s[i]) == 0
      g[t[i]] << s[i]
    end
  else
    g[t[i]] = [s[i]]
  end
end

文字列sから文字列tを見たハッシュhと、文字列tから文字列sを見たハッシュgを取得しています。

flat.rb
puts h.flatten(-1) == g.invert.flatten(-1) ? 'Yes' : 'No'

invertでハッシュの逆(keyとvalueの入れ替え)を取得し比較します。

Python

辞書のkeyとvalueを1行で入れ替える -Qiitaにありますように、辞書の逆を求めるのが大変そうなので、Pythonはお休みします。機械学習に関係なさそうだし

Ruby 技術者認定試験 Silverを勉強した時、invertflattenなんて使わないよね、と思っていましたが、実際に使用することになりびっくり。
基礎学習って、必要ですね。

Ruby
コード長 (Byte) 375
実行時間 (ms) 514
メモリ (KB) 22780

まとめ

  • ABC 110 C を解いた
  • Ruby に詳しくなった

参照したサイト
辞書のkeyとvalueを1行で入れ替える
instance method Hash#flatten

2
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0