File tree 3 files changed +78
-0
lines changed
014.Longest Common Prefix
3 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ # @param {Integer} x
2
+ # @return {Integer}
3
+ def reverse ( x )
4
+ neg = x < 0
5
+
6
+ x = x . abs
7
+ s = ''
8
+
9
+ x /= 10 while x > 0 && ( x % 10 ) . zero?
10
+
11
+ while x > 0
12
+ s += ( x % 10 ) . to_s
13
+ x /= 10
14
+ end
15
+
16
+ s = neg ? '-' + s : s
17
+
18
+ # have to explicitly constraint the int boundary as per the dummy test case
19
+ res = s . to_i
20
+ res <= 214_748_364_7 && res >= -214_748_364_8 ? res : 0
21
+ end
Original file line number Diff line number Diff line change
1
+ # @param {String} s
2
+ # @return {Integer}
3
+ def roman_to_int ( s )
4
+ hash = Hash [
5
+ 'I' => 1 ,
6
+ 'V' => 5 ,
7
+ 'X' => 10 ,
8
+ 'L' => 50 ,
9
+ 'C' => 100 ,
10
+ 'D' => 500 ,
11
+ 'M' => 1000 ,
12
+ 'IV' => 4 ,
13
+ 'IX' => 9 ,
14
+ 'XL' => 40 ,
15
+ 'XC' => 90 ,
16
+ 'CD' => 400 ,
17
+ 'CM' => 900
18
+ ]
19
+ res = 0
20
+ i = 0
21
+ while i < s . length
22
+ if i < s . length - 1 && !hash [ s [ i ..i +1 ] ] . nil?
23
+ res += hash [ s [ i ..i +1 ] ]
24
+ i += 2
25
+ else
26
+ res += hash [ s [ i ] ]
27
+ i += 1
28
+ end
29
+ end
30
+
31
+ res
32
+ end
Original file line number Diff line number Diff line change
1
+ # @param {String[]} strs
2
+ # @return {String}
3
+ def longest_common_prefix ( strs )
4
+ return '' if strs . nil? || strs . length . zero?
5
+
6
+ return strs [ 0 ] if strs . length == 1
7
+
8
+ idx = 0
9
+ while idx < strs [ 0 ] . length
10
+ cur_char = strs [ 0 ] [ idx ]
11
+
12
+ str_idx = 1
13
+ while str_idx < strs . length
14
+ return idx > 0 ? strs [ 0 ] [ 0 ..idx -1 ] : '' if strs [ str_idx ] . length <= idx
15
+
16
+ return '' if strs [ str_idx ] [ idx ] != cur_char && idx . zero?
17
+ return strs [ 0 ] [ 0 ..idx - 1 ] if strs [ str_idx ] [ idx ] != cur_char
18
+ str_idx += 1
19
+ end
20
+
21
+ idx += 1
22
+ end
23
+
24
+ idx > 0 ? strs [ 0 ] [ 0 ..idx ] : ''
25
+ end
You can’t perform that action at this time.
0 commit comments