Ruby解题分享-Implement strStr() && Search Insert Position

下雨的周六...偷懒最适合...


Implement strStr()

题目连结:https://leetcode.com/problems/implement-strstr/
整理如下

def str_str(haystack, needle)

end

p str_str("hello", "ll") #=>2
p str_str("aaaaa", "bba") #=>-1
p str_str("", "") #=>0

题目重点:如果haystack是空字串回传什麽? 可以向面试官提问。
真贴心,但是面试官应该不会问这题??!!

一样,这种给"目标"比对"值"的解法,跑回圈比对都是菜鸟我第一个会想到的,但是学什麽语言就多用那语言的优点吧。这题到後面就是看怎麽写比较"好看"了。
我还用split来解,有够丑

def str_str(haystack, needle)
  ans = haystack.index(needle)
  if ans != nil
    ans
  else
    -1
  end
end

这题主要语法是index用法,字串、阵列、杂凑都可以使用。

2.7.3 :001 > [0, 1, 2, 3, 4].index(3)
 => 3 
2.7.3 :002 > [0, 1, 2, 3, 4].index(5)
 => nil 
2.7.3 :003 > "今天下雨".index("下雨")
 => 2 
2.7.3 :004 > "今天下雨".index("太阳")
 => nil 
2.7.3 :005 > "今天下雨".index("天下")
 => 1 
2.7.3 :006 > {a: 2, b: 3}.index(2)
 => :a 
2.7.3 :007 > {a: 2, b: 3}.index(3)
 => :b 
2.7.3 :008 > {a: 2, b: 3}.index(:a)
 => nil 

解法减化後

def str_str(haystack, needle)
  ans = haystack.index(needle)
  ans != nil ? ans : -1
end

def str_str(haystack, needle)
  haystack.index(needle) != nil ? haystack.index(needle) : -1
end

def
  return -1 unless haystack.index(needle)
  return haystack.index(needle)
end

第一种写法,三元运算子简化。
第二种,可能需要知道nil与false在Ruby世界中代表什麽。
第三种unless是if的相反,比较像"除非",所以第一句念起来是"回传 -1 除非 haystack.index(needle)",一样如果不熟练布林值语意,反而看不懂。

def str_str(haystack, needle)
  return -1 unless haystack.index(needle)
  haystack.index(needle)
end

#上面正确,下面错误,可以观察一下。

def str_str(haystack, needle)
  -1 unless haystack.index(needle)
  haystack.index(needle)
end

Search Insert Position

题目连结:https://leetcode.com/problems/search-insert-position/
重点:nums contains distinct values sorted in ascending order. 正升且无重复。
等於告诉了我们target如果是0,该怎麽处理。

整理

def search_insert(nums, target)

end

p search_insert([1,3,5,6], 5)  #=> 2
p search_insert([1,3,5,6], 2)  #=> 1
p search_insert([1,3,5,6], 7)  #=> 4
p search_insert([1,3,5,6], 0)  #=> 0
p search_insert([1], 0)  #=> 0

Ruby中迭代先each,each不够时,记得还有map就好。

#先不简化
def search_insert(nums, target)
  nums.each_with_index do |num, index|  
    if num >= target 
      return index 
    end  #大於0的目标与里面的值的关系是,刚好相等时回报位置,比较小时取代里面值的位置
  end
  nums.size
end

def search_insert(nums, target)
  nums.each_with_index do |num, index|
    return index if num >= target
  end
  nums.size
end

<<:  遵守政策的管理制度

>>:  Ruby解题分享-Maximum Subarray

RISC V::中断与异常处理 -- PLIC 介绍

本文目标 认识 PLIC, IRQ 与 ISR 综合先前所学,应用在实际案例上 进入正题 PIC P...

【Day 09】 实作 - 透过 AWS 服务 - AppFlow 把 Google Analytics 资料存放至 AWS 中 ( 2 )

大家好~昨天我们建立好 Google Analytics 与 AWS 连线,现在我们就可以透过 AW...

Re-architect with UseCase driven design

Re-architect 大家应该都很常说,或是很习惯使用到一个词 - 重构(Refactoring...

Day 25 - Vue CLI 与 npm

在进行开发的时候,我们常常会下载各式各样的library,如果我们没有一个工具来帮助我们维护这些套件...

Twinkle Tray 多显示器屏幕亮度调节工具

Twinkle Tray是一款支持多显示器的屏幕亮度调节工具,让你可以在一块屏幕上调节所有的显示器亮...