-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_6_leet.rb
146 lines (108 loc) · 2.59 KB
/
4_6_leet.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def myst(a,b)
x=a
y=b
until x == y
if x>y
x = x-y
else
y = y-x
end
end
x
end
#
# Complete the 'isPossible' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER a
# 2. INTEGER b
# 3. INTEGER c
# 4. INTEGER d
#
# only move up or right!
# recursion:
# return nothing if a > c OR b > d
# if a==c && b == d, return true
#return "No" at the end, below all logic
#
# inductive step: recursively search with adds to a or b
def isPossible(a, b, c, d)
return "Yes" if a==c && b==d
return if a > c || b > d
p "Spot: (#{a},#{b})"
added_val = a + b
isPossible(a,added_val,c,d)
isPossible(added_val,b,c,d)
"No"
end
# p isPossible(1,4,5,9) => "Yes"
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Boolean}
def is_valid_bst(root)
return unless root
if root.left
return false unless root.left.val < root.val
elsif root.right
return false unless root.right.val > root.val
end
is_valid_bst(root.left) && is_valid_bst(root.right)
end
# @param {Character[]} s
# @return {Void} Do not return anything, modify s in-place instead.
def reverse_string(s)
stop_idx = s.length/2
(0...stop_idx).each do |idx|
s[idx], s[-idx-1] = s[-idx-1], s[idx]
end
end
# @param {Integer} x
# @return {Integer}
def reverse(x)
reversed_num=x.to_s.split("").reverse.join("").to_i
return 0 unless reversed_num < 2**31 && reversed_num > -2**31
x >0 ? reversed_num : -reversed_num
end
# @param {String} s
# @param {String} t
# @return {Boolean}
def is_anagram(s, t)
s.split("").sort == t.split("").sort
end
# @param {String} s
# @return {Boolean}
def is_palindrome(s)
alphabet = ('a'..'z').to_a
nums = ('0'..'9').to_a
alphabet.concat(nums)
filtered_str = ""
s.each_char do |char|
if alphabet.include?(char.downcase)
filtered_str += char.downcase
end
end
filtered_str == filtered_str.reverse
end
# @param {String[]} strs
# @return {String}
def longest_common_prefix(strs)
lcp=""
return lcp if strs.empty?
min_size = strs.min_by(&:length).length
(0...min_size).each do |idx|
if strs.all? {|arr| arr[idx] == strs[0][idx]}
lcp += strs[0][idx]
else
break
end
end
lcp
end