不得不说Ruby的核心api就自带解题的爽点,例如transpose和squeeze。
先是这道会员简单题,大家自己体会
422. 有效的单词方块
# @param {String[]} words
# @return {Boolean}
def valid_word_square(words)
len = words.map {|it| it.length}.max
words_t = words.map {|it| if it.length < len then it.each_char.to_a.concat(Array.new(len-it.length,"")) else it.each_char.to_a end }.transpose
for i in 0...words.length
if words[i] != words_t[i].join
return false
end
end
return true
end
然后是这道中等题
443. 压缩字符串
# @param {Character[]} chars
# @return {Integer}
def compress(chars1)
c = chars1.join.squeeze
i = 0
j = 0
ans = []
ans << c[0]
cnt = 0
while i < c.length && j < chars1.length
if c[i] == chars1[j]
cnt += 1
j += 1
else
if cnt > 1
ans = ans.concat(cnt.to_s.each_char.to_a)
end
ans << chars1[j]
cnt = 1
i += 1
j += 1
end
if j == chars1.length - 1 && c[i] == chars1[j]
cnt += 1
if cnt > 1
ans = ans.concat(cnt.to_s.each_char.to_a)
end
chars1.clear
chars1 = chars1.concat(ans)
break
end
if j == chars1.length - 1 && c[i] != chars1[j]
if cnt > 1
ans = ans.concat(cnt.to_s.each_char.to_a)
end
ans << chars1[j]
chars1.clear
chars1 = chars1.concat(ans)
break
end
end
end