You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Write code to reverse a C-Style String. (C-String means that 'abcd' is represented as five characters, including the null character.)
3
+
4
+
5
+
In C and C++, strings are typically represented as char arrays that have a null terminator. A null terminator means that the string ends with a '\0' character (which has ASCII code 0)
6
+
7
+
'''
8
+
9
+
10
+
# clarification questions:
11
+
# 1) input is a string ending with '\0'
12
+
# 2) i cannot use .reverer(), right?
13
+
importcopy
14
+
defstrReverse(string):
15
+
string=copy.deepcopy(string)
16
+
string=string[:-1]
17
+
lst=list(string)
18
+
lst.reverse() # the same as: reverse(lst)
19
+
lst.append('\0')
20
+
returnstr(lst)
21
+
22
+
# the same as list's reverse() function
23
+
defreverse(lst):
24
+
# swap from the beginning to the middle point of the array
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.
3
+
FOLLOW UP
4
+
Write the test cases for this method.
5
+
'''
6
+
7
+
# clarification question:
8
+
# 1) does order matter? If not simple use ''.join(set(string) will work (yes, it matters)
9
+
# 2) for duplicates, we keep its first occurance. is that correct? (yes)
10
+
# 3) what do you mean by 'An extra copy of the array'?
11
+
# i plan to use a dictionary to store unique chars, is this allowed?
12
+
# (yes)
13
+
# 4) can I use python's set? (yes)
14
+
# 5) can I use python's collections library? (yes)
15
+
16
+
# solution 1: use Set
17
+
defremove_duplicates_1(string):
18
+
uniques=list(set(string))
19
+
lst=list(string)
20
+
foriinrange(len(lst)):
21
+
char=lst[i]
22
+
ifcharinuniques:
23
+
uniques.remove(char)
24
+
else:
25
+
lst[i] =''
26
+
return''.join(lst)
27
+
28
+
# solution 2: use OrderedDict
29
+
fromcollectionsimportOrderedDict
30
+
defremove_duplicates_2(string):
31
+
return''.join(OrderedDict.fromkeys(string))
32
+
33
+
34
+
# solution 3: scan from the beginning, remove all duplicates of index - O(n^2)
35
+
defremove_duplicates_3(string):
36
+
lst=list(string)
37
+
foriinrange(len(lst)-1):
38
+
char=lst[i]
39
+
forjinrange(i+1,len(lst)):
40
+
iflst[j] ==char:
41
+
lst[j] =''
42
+
return''.join(lst)
43
+
44
+
# solution 4: if order does not matter, use Set
45
+
defremove_duplicates_4(string):
46
+
return''.join(set(string))
47
+
48
+
49
+
# solution 5: if order does not matter (cannot use Set):
0 commit comments