iT邦幫忙

1

Ruby--Find the Difference

  • 分享至 

  • xImage
  •  

Yes


Find the Difference

題目連結:https://leetcode.com/problems/find-the-difference/
題目重點:t字串大於s字串,只隨機多"一個"字母。

大家都有的黑魔法,byte轉換。

2.7.3 :048 > "a".bytes
 => [97] 
2.7.3 :049 > "a".ord
 => 97 
2.7.3 :050 > "aa".bytes
 => [97, 97] 
2.7.3 :051 > "aa".ord
 => 97 
2.7.3 :052 > [97, 97].sum
 => 194 
2.7.3 :053 > "aa".sum
 => 194 

依照題目來解

def find_the_difference(s, t)
  (t.sum - s.sum).chr
end

2.7.3 :054 > 99.chr
 => "c" 

不跑迴圈不行

def find_the_difference(s, t)
  #s與t先轉換成有序陣列
  #一個一個比較,回array內那個不相同的
end

2.7.3 :058 > "acade".chars
 => ["a", "c", "a", "d", "e"] 
2.7.3 :059 > "acade".split""
 => ["a", "c", "a", "d", "e"] 
2.7.3 :060 > ["a", "c", "a", "d", "e"].sort
 => ["a", "a", "c", "d", "e"] 

ans

def find_the_difference(s, t)
  s_arr = s.chars.sort
  t_arr = t.chars.sort
  i = 0
  while i < t.length
    if t_arr[i] != s_arr[i]
      return t_arr[i]
    else
      i += 1
    end
  end
end

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言