iT邦幫忙

1

Ruby幼幼班--Rotate String

  • 分享至 

  • xImage
  •  

Yes

堅持傳教K-pop...就可以堅持每天解題??


Rotate String

題目連結:https://leetcode.com/problems/rotate-string/
題目重點:goal是s的第一個字母(最左),移到最後(最右),n次後型成的。
整理:

# @param {String} s
# @param {String} goal
# @return {Boolean}
def rotate_string(s, goal)
    
end

p rotate_string("abcde", "cdeab")
p rotate_string("abcde", "abced")

觀察法

A shift on s consists of moving the leftmost character of s to the rightmost position.
其實就是e後面依序增加a,b,c,d,e。

2.7.3 :006 > x = "abcde" 
 => "abcde" 
2.7.3 :007 > x = x + "a"
 => "abcdea" 
2.7.3 :008 > x = x + "b"
 => "abcdeab" 
2.7.3 :009 > x = x + "c"
 => "abcdeabc" 
2.7.3 :010 > x = x + "d"
 => "abcdeabcd" 
2.7.3 :011 > x = x + "e"
 => "abcdeabcde" 
 
#那其實就是
2.7.3 :012 > "abcde" + "abcde"
 => "abcdeabcde" 
2.7.3 :013 > "abcde" * 2
 => "abcdeabcde" 

既然,goal是依照這個規律形成的,那也代表goal一定會包含在這裡。

def rotate_string(s, goal)
  (s * 2).include?(goal)   #Ruby語法有?符號,就多為判斷句...還沒學到例外的..
end

送出解答發現還有一個"aa"與"a"的比較,兩個長度不一樣。

def rotate_string(s, goal)
  if s.length == goal.length
    (s + s).include?(goal)
  else
    false
  end
end

#雙判斷,直接簡化吧
def rotate_string(s, goal)
  s.length == goal.length && (s + s).include?(goal)
end

rotate!

另外Ruby本身有這語法。

2.7.3 :018 > "abcde".split("").rotate!
 => ["b", "c", "d", "e", "a"] 
2.7.3 :019 > ["b", "c", "d", "e", "a"].rotate!
 => ["c", "d", "e", "a", "b"] 
2.7.3 :020 > ["c", "d", "e", "a", "b"].rotate!
 => ["d", "e", "a", "b", "c"] 

用這語法解,leetcode也給過,這邊跳過了。

又想跑迴圈了...

雖然覺得自己刷題還是很菜,但至少已經知道如果要跑迴圈檢驗資料,那先想出跑幾次,怎麼跑,終止條件。

def rotate_string(s, goal)
  #迴圈,無限跑還是有次數?  這題次數不可能超過s.size。
  #怎麼跑
  #終止條件,這個題目已經告訴我們了.
  s == goal
end

怎麼跑?

一樣由說明看,string最左移到最右。

2.7.3 :037 > s = "abcde"
 => "abcde" 
2.7.3 :038 > s[0]
 => "a" 
2.7.3 :039 > s[4] # 4 = "abcde".size - 1
 => "e" 
2.7.3 :040 > s[1..4]
 => "bcde" 
2.7.3 :041 > s[1..-1] #陣列語法
 => "bcde" 
2.7.3 :042 > s[1..-1] + s[0]
 => "bcdea" 
2.7.3 :043 > s
 => "abcde" 
2.7.3 :044 > s = s[1..-1] + s[0]
 => "bcdea" 
2.7.3 :045 > s = s[1..-1] + s[0]
 => "cdeab" 

so

def rotate_string(s, goal)
  s.size.times do 
    s = s[1..-1] + s[0] 
  end  #迴圈與怎麼跑
  #缺終止條件
  s == goal
  #有可能5次跑完 s 還是 != goal,那就回傳false
  false
end

def rotate_string(s, goal)
  s.size.times do 
    return true if s == goal
    s = s[1..-1] + s[0]
  end  
  false
end

解完...


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

尚未有邦友留言

立即登入留言