-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.py
More file actions
1745 lines (1357 loc) · 39.1 KB
/
strings.py
File metadata and controls
1745 lines (1357 loc) · 39.1 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import re
import sys
from math import e, log
def rotate_array(k, i):
l = len(i)
return i[l - k:l] + i[0:l - k]
def reverse_words_string(v):
return " ".join(list(reversed(v.split())))
def eval_reverse_polish_notation(i):
stack = []
for v in i:
stack.append(v)
if v in ["+", "*", "-", "/"]:
a, b, c = stack.pop(), stack.pop(), stack.pop()
stack.append(eval("{}{}{}".format(c, a, b)))
return stack.pop()
def is_isomorphic_string(s, t):
if s is None or t is None or len(s) != len(t):
return False
m = dict()
for i, c1 in enumerate(s):
c2 = t[i]
if c1 in m:
if m[c1] != c2:
return False
else:
if c2 in list(m.values()):
return False
m[c1] = c2
return True
class Word(object):
def __init__(self, word, steps):
self.word = word
self.steps = steps
def word_ladder_1(begin, end, words):
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
queue = list()
queue.append(Word(begin, 1))
words.append(end)
while queue:
top = queue.pop()
word = top.word
if word == end:
return top.steps
for i, c in enumerate(word):
for ch in ascii_lowercase:
new_word = word
if c != ch:
tmp = list(word)
tmp[i] = ch
new_word = "".join(tmp)
if new_word in words:
queue.append(Word(new_word, top.steps + 1))
words.remove(new_word)
return 0
def word_ladder_2(begin, end, words):
pass
def find_kth(k, a, b, s1, s2):
if s1 >= len(a):
return b[s2 + k - 1]
if s2 >= len(b):
return a[s1 + k - 1]
if k == 1:
return min(a[s1], b[s2])
m1 = s1 + k / 2 - 1
m2 = s2 + k / 2 - 1
if m1 < len(a):
mid1 = a[m1]
else:
mid1 = sys.maxsize
if m2 < len(b):
mid2 = b[m2]
else:
mid2 = sys.maxsize
if mid1 < mid2:
return find_kth(k - k / 2, a, b, m1 + 1, s2)
else:
return find_kth(k - k / 2, a, b, s1, m2 + 1)
def find_median_sorted_array(a, b):
total = len(a) + len(b)
if total % 2 == 0:
return (find_kth(total / 2 + 1, a, b, 0, 0) +
find_kth(total / 2, a, b, 0, 0, )) / 2
else:
return find_kth(total / 2 + 1, a, b, 0, 0)
def find_kth_largest_elm(a, k):
a = sorted(a)
return a[len(a) - k]
def regexp_match(a, b):
if len(b) == 0:
return len(a) == 0
if len(b) == 1 or b[1] != "*":
if len(a) < 1 or (b[0] != '.' and a[0] != b[0]):
return False
return regexp_match(a[1:], b[1:])
else:
i = -1
while i < len(a) and (i < 0 or b[0] == '.' or b[0] == a[i]):
if regexp_match(a[i + 1:], b[2:]):
return True
i += 1
return False
def candy(rating):
if rating is None or len(rating) == 0:
return 0
candies = list()
for i in range(len(rating)):
candies.append(0)
candies[0] = 1
for i in range(1, len(rating)):
if rating[i] > rating[i - 1]:
candies[i] = candies[i - 1] + 1
else:
candies[i] = 1
result = candies[len(rating) - 1]
for i in range(len(rating) - 2, 0, -1):
cur = 1
if rating[i] > rating[i + 1]:
cur = candies[i + 1] + 1
result += max(cur, candies[i])
candies[i] = cur
return result
def merge_intervals(intervals):
intervals = sorted(intervals)
result = []
pre = intervals[0]
for i in range(0, len(intervals)):
current = intervals[i]
if pre[1] > current[0]:
pre = [pre[0], max(current[1], pre[1])]
else:
result.append(pre)
pre = current
result.append(pre)
return result
def insert_interval(intervals, new):
result = []
for _, i in enumerate(intervals):
if i[1] < new[0]:
result.append(i)
elif i[0] > new[1]:
result.append(new)
new = i
elif i[1] >= new[0] or i[0] <= new[1]:
new = [min(i[0], new[0]),
max(new[1], i[1])]
result.append(new)
return result
def sum_1(numbers, target):
hash_map = dict()
for i, n in enumerate(numbers):
if n in hash_map:
return [hash_map.get(n), i]
else:
hash_map[target - n] = i
def sum_2(numbers, target):
i, j = 0, len(numbers) - 1
while i < j:
x = numbers[i] + numbers[j]
if x < target:
i += 1
elif x > target:
j -= 1
else:
return [i + 1, j + 1]
class TwoSum(object):
def __init__(self):
self.hash_map = dict()
def add(self, num):
if num in self.hash_map:
self.hash_map[num] += 1
else:
self.hash_map[num] = 1
def find(self, num):
for key, value in self.hash_map.items():
target = num - key
if target in self.hash_map:
if key == target and value < 2:
continue
return True
return False
def atoi(s):
if not s:
return 0
flag = "+"
if s[0] == "-":
flag = "-"
res = 0
for i, ch in enumerate(s):
if "0" <= ch <= "9":
res = res * 10 + int(ch)
if flag == "-":
res *= -1
if res > sys.maxsize:
return sys.maxsize
return res
def sum_3(arr):
arr = sorted(arr)
res = list()
for i1, n in enumerate(arr):
i2 = i1 + 1
while i2 < len(arr):
i3 = i2 + 1
while i3 < len(arr):
if arr[i1] + arr[i2] + arr[i3] == 0:
if not [arr[i1], arr[i2], arr[i3]] in res:
res.append([arr[i1], arr[i2], arr[i3]])
i3 += 1
i2 += 1
return res
def sum_4(arr, target):
arr = sorted(arr)
res = list()
for i1, n in enumerate(arr):
i2 = i1 + 1
while i2 < len(arr):
i3 = i2 + 1
while i3 < len(arr):
i4 = i3 + 1
while i4 < len(arr):
if arr[i1] + arr[i2] + arr[i3] + arr[i4] == target:
if not [arr[i1], arr[i2], arr[i3], arr[i4]] in res:
res.append([arr[i1], arr[i2], arr[i3], arr[i4]])
i4 += 1
i3 += 1
i2 += 1
return res
def sum_3_closest(arr, target):
m = sys.maxsize
res = 0
arr = sorted(arr)
for i, n in enumerate(arr):
j = i + 1
k = len(arr) - 1
while j < k:
s = n + arr[j] + arr[k]
diff = abs(s - target)
if diff == 0:
return s
if diff < m:
m = diff
res = s
if s <= target:
j += 1
else:
k -= 1
return res
def sum_3_pointer(arr):
res = []
arr = sorted(arr)
for i, n in enumerate(arr):
if i == 0 or arr[i] > arr[i - 1]:
j = i + 1
k = len(arr) - 1
while j < k:
s = n + arr[j] + arr[k]
if s == 0:
res.append([n, arr[j], arr[k]])
j += 1
k -= 1
while j < k and arr[j] == arr[j - 1]:
j += 1
while j < k and arr[k] == arr[k + 1]:
k -= 1
elif s < 0:
j += 1
else:
k -= 1
return res
def merge_two_sorted_array(a, b):
i, j, k, res = 0, 0, len(a) + len(b) - 2, list()
while k >= 0:
k -= 1
if a[i] < b[j]:
res.append(a[i])
i += 1
else:
res.append(b[j])
j += 1
while i < len(a):
res.append(a[i])
i += 1
while j < len(b):
res.append(b[j])
j += 1
return res
def longest_valid_parentheses(string):
x, i = "()", 0
while string.find(x) != -1:
x += "()"
i += 1
return i * 2
def strStr(haystack, needle):
if not (haystack or needle or len(needle)):
return 0
for i, ch in enumerate(haystack):
if needle in haystack[i:i + len(needle)]:
return i
return -1
def min_size_subarray_sum(arr, target):
arr = sorted(arr, reverse=True)
res = 1
while res <= len(arr):
if sum(arr[0:res]) >= target:
return res
res += 1
return 0
def search_insert(arr, target):
if target in arr:
return arr.index(target)
arr.append(target)
return sorted(arr).index(target)
def longest_consecutive_sequence(arr):
if len(arr) == 0:
return 0
res = 1
for e in arr:
left = e - 1
right = e + 1
count = 1
while left in arr:
arr.remove(left)
count += 1
left -= 1
while right in arr:
arr.remove(right)
count += 1
right += 1
res = max(count, res)
return res
def zig_zag_conversion(string, rows):
"""
rows = 3
string = PAYPALISHIRING
res = PAHNAPLSIIGYIR
P A H N
A P L S I I G
Y I R
item: 1 2 3 4 5 6 7 8 9 10 11
row : 1 2 3 2 1 2 3 2 1 2 3
col : 1 1 1 2 3 3 3 4 5 5 5
rows = 4
string = PPAYPAASSRIHHSGR
res = PAHPASHSAPSIGYRR
P A H
P A S H S
A P S I G
Y R R
row: 1 2 3 4 3 2 1
col: 1 1 1 1 2 3 4
"""
zig_zag, row, col, add, res = [[] for i in range(rows)], 0, 0, True, ""
for ch in string:
zig_zag[row].append(ch)
if add:
row += 1
else:
row += -1
if row == rows - 1:
add = False
elif row == 0:
add = True
for i in range(rows):
res += ''.join(zig_zag[i])
return res
def add_binary(a, b):
return bin(int(a, 2) + int(b, 2))[2:]
def add_binary_orig(x, y):
"""
11 1 -> 11 01
flag = False => 1 + 1 = 0 flag = True
flag = True => 1 + 0 + f = 0 flag = True
flag = True => 0 + 0 + f = 1 flag = False
100
"""
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry != 0: result = '1' + result
return result.zfill(max_len)
def length_last_word(string):
return len(string.strip()) - string.strip().rfind(' ')
def triangle(arr):
res = [min(arr[len(arr) - 1])]
index = arr[len(arr) - 1].index(res[0])
for i in range(len(arr) - 2, 0, -1):
res.append(min(arr[i][index - 1: index + 1]))
res.append(arr[0][0])
return sum(res)
def contains_duplicate(arr):
d = dict()
for n in arr:
if n in d:
return True
d[n] = n
return False
def contains_duplicate_two(arr, k):
d = dict()
for i, n in enumerate(arr):
if n in d:
if i - d[n] <= k:
return True
else:
d[n] = i
return False
def insertion_sort(arr):
for i, key in enumerate(arr):
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def exercise_1(n):
z = 0
o = 0
for i in range(n):
j = 1
while j <= n:
z += 1
j *= 2
o += 1
o += 1
return z
def remove_duplicate_from_sorted_array(arr):
i = 0
while True:
if i >= len(arr) - 1:
break
if arr[i] == arr[i + 1]:
del arr[i]
i += 1
return len(arr), arr
def remove_duplicate_from_sorted_array_two(arr):
i = 0
while True:
if i >= len(arr) - 2:
break
if arr[i] == arr[i + 1] == arr[i + 2]:
del arr[i]
i += 1
return len(arr), arr
def remove_element(arr, elem):
i, j = 0, 0
for j in range(len(arr)):
if arr[j] != elem:
arr[i] = arr[j]
i += 1
return i
def move_zero(arr):
for i in range(len(arr)):
if arr[i] == 0:
del arr[i]
arr.append(0)
return arr
def trap_rain_water(height):
if height is None or len(height) <= 2:
return 0
left, right = [0] * len(height), [0] * len(height)
maximum, left[0] = height[0], height[0]
# scan from left to right
for i in range(len(height)):
if height[i] < maximum:
left[i] = maximum
else:
left[i] = height[i]
maximum = height[i]
# scan from right to left
maximum = height[len(height) - 1]
right[len(height) - 1] = height[len(height) - 1]
for i in range(len(height) - 2, 0, -1):
if height[i] < maximum:
right[i] = maximum
else:
right[i] = height[i]
maximum = height[i]
return sum([min(left[i], right[i]) - h for i, h in enumerate(height)])
def summary_range(arr):
result = []
start = arr[0]
for i, item in enumerate(arr[:len(arr) - 1]):
if item + 1 == arr[i + 1]:
end = item + 1
else:
if end:
result.append(str(start) + "->" + str(end))
else:
result.append(str(item))
start = arr[i + 1]
end = None
else:
if end:
result.append(str(start) + "->" + str(end))
else:
result.append(str(arr[len(arr) - 1]))
return result
def one_edit_distance(s, t):
if s is None or t is None:
return False
m, n = len(s), len(t)
if abs(m - n) > 1:
return False
i, j, count = 0, 0, 0
while i < m and j < n:
if s[i] == t[j]:
i += 1
j += 1
else:
count += 1
if count > 1:
return False
if m > n:
i += 1
elif m < n:
j += 1
else:
i += 1
j += 1
if i < m or j < n:
count += 1
if count == 1:
return True
return False
def shortest_word_distance(words, a, b):
distance = None
index = dict()
index[a], index[b] = None, None
for i, word in enumerate(words):
if word == a:
index[a] = i
if word == b:
index[b] = i
if not index[a] is None and not index[b] is None:
if distance:
distance = min(distance, abs(index[a] - index[b]))
else:
distance = abs(index[a] - index[b])
index[a], index[b] = None, None
if word == a:
index[a] = i
if word == b:
index[b] = i
return distance
def shortest_word_distance_three(words, a, b):
distance = None
idx = None
for i, w in enumerate(words):
if w == a and idx:
distance = min(distance, abs(i - idx)) if distance else abs(i - idx)
idx = i
elif w == a:
idx = i
return distance
def find_min_rotated_sorted_arr(arr):
i, j = 0, len(arr) - 1
while True:
m = (i + j) / 2
if arr[m] > arr[i]:
i = m
else:
j = m
if i + 1 == j:
break
return arr[i] if arr[i] < arr[j] else arr[j]
def find_min_rotated_sorted_arr_dup(arr):
i, j = 0, len(arr) - 1
while True:
if arr[i] == arr[j]:
i += 1
continue
m = (i + j) / 2
if arr[m] < arr[i]:
i = m
else:
j = m
if i + 1 == j:
break
return arr[i] if arr[i] < arr[j] else arr[j]
def binary_search(arr, target):
i, j = 0, len(arr) - 1
while i + 1 < j:
m = (i + j) / 2
if target > arr[m]:
i = m
else:
j = m
if arr[i] == target:
return i
elif arr[j] == target:
return j
return -1
def search_range(arr, target):
idx = binary_search(arr, target)
if idx == -1:
return -1, -1
i, j = idx, idx
break_left, break_right = False, False
while not (break_right and break_left) and (j + 1 < len(arr)):
if i != 0:
if arr[i - 1] == target:
i -= 1
else:
break_left = True
else:
break_left = True
if arr[j + 1] == target:
j += 1
else:
break_right = True
return i, j
def guess_number(n):
def guess(num):
res = 153
if num == res:
return 0
elif num < res:
return -1
else:
return 1
i, j = 0, n
while i + 1 < j:
m = (i + j) / 2
x = guess(m)
if x == 0:
return m
elif x > 0:
j = m
else:
i = m
def solver():
n = 1000
for i in range(1, n, 1):
if i + log(i, e) == 0:
return i
def search_rotated_sorted_array(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
m = left + (right - left) / 2
if target == arr[m]:
return m
if arr[left] <= arr[m]:
if arr[left] <= target < arr[m]:
right = m - 1
else:
left = m + 1
else:
if arr[m] < target <= arr[right]:
left = m + 1
else:
right = m - 1
return -1
def search_rotated_sorted_array_two(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
m = (left + right) / 2
if target == arr[m]:
return m
if arr[left] <= arr[m]:
if arr[left] <= target < arr[m]:
right = m - 1
else:
left = m + 1
elif arr[left] > arr[m]:
if arr[m] < target <= arr[right]:
left = m + 1
else:
right = m - 1
else:
left += 1
return -1
class Stack(object):
def __init__(self):
self.min = None
self.stack = list()
def push(self, x):
self.stack.append(x)
if not self.min:
self.min = x
else:
if self.min > x:
self.min = x
def largest_rect_histogram(arr):
stack, m = list(), 0
i = 0
while i < len(arr):
if not stack:
stack.append(i)
i += 1
continue
if arr[i] >= arr[stack[len(stack) - 1]]:
stack.append(i)
i += 1
else:
h = arr[stack.pop()]
w = i if not stack else i - stack[len(stack) - 1] - 1
m = max(h * w, m)
while stack:
h = arr[stack.pop()]
w = i if not stack else i - stack[len(stack) - 1] - 1
m = max(h * w, m)
return m
def valid_anagram(s, t):
if len(s) != len(t):
return False
arr = [0] * 26
for i, ch in enumerate(s):
arr[ord(ch) - ord('a')] += 1
arr[ord(t[i]) - ord('a')] -= 1
for i, x in enumerate(arr):
if x != 0:
return False
return True
def palindrome_pairs(s):
pairs = []
data = dict()
for i, w in enumerate(s):
data[w[::-1]] = i
for i, w in enumerate(s):
if w in data:
pairs.append([data[w], i])
return pairs
def longest_sub_str(s):
res = ""
for i in range(len(s)):
tmp = dict()
for j, ch in enumerate(s, i):
if ch in tmp:
res = s[i:j] if len(s[i:j]) > len(res) else res
break
else:
tmp[ch] = j
return res
def longest_sub_str_2_unique_char(s):
m, start, data = 0, 0, dict()
for i, ch in enumerate(s):
data[ch] = 1 if ch not in data else data[ch] + 1
if len(data) > 2:
m = max(m, i - start)
while len(data) > 2:
t = s[start]
count = data[t]
if count > 1:
data[t] = count - 1
else:
del data[t]
start += 1
return max(m, len(s) - start)
def min_window_sub_str(s, t):
pass
def get_target_num(arr, target):
pass
def flip_game(s):
result = []
s = list(s)
for i in range(len(s) - 1):
if s[i] == s[i + 1] and s[i] == '+':
s[i], s[i + 1] = '-', '-'
result.append(''.join(s))
s[i], s[i + 1] = '+', '+'
return result
def flip_game_two(s):
s = list(s)
for i in range(len(s) - 1):
if s[i] == '+' and s[i + 1] == '+':
s[i], s[i + 1] = '-', '-'