Ruby幼幼班--Rotate String

坚持传教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

解完...


<<:  型一错误与型二错误(Type I error & Type II error)

>>:  档案总管右半边Delphi TListView

实用且有效的CISSP考试秘诀!

来自Luke的实用且有效的CISSP考试秘诀! 很棒!! 阅读 (Reading) 作练习题 (Pr...

Youtube Analytics API 教学  -  期待多元性别出现 'gender' 维度

「鲑鱼均,因为一场鲑鱼之乱被主管称为鲑鱼世代,广义来说以年龄和脸蛋分类的话这应该算是一种 KNN 的...

建立 Line Bot(2)

今天接着完成 Line Bot 的设置。 加入 Line Bot 昨天我们注册了 Line Deve...

[全民疯AI系列] 完赛总结

全民疯AI系列完赛总结 参加这次的铁人赛也算是完成我在学习上的一个里程碑!本来还认为写文章比较耗时(...

Day24 Plugin 从零开始到上架 - FlutterPlugin与 MethodCallHandler

InstagramBasicDisplayApiPlugin class InstagramBasi...