GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Strings/longest_common_prefix.py at master · code3002/coding-problems Expand file tree/ Copy pathlongest_common_prefix.pyMore file actions 74 lines (57 loc) · 1.79 KB / Copy pathlongest_common_prefix.pyFile metadata and controls74 lines (57 loc) · 1.79 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 ''' Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string ''. Input: ['flower', 'flow', 'flight'] Output: 'fl' Input: ['dog', 'racecar', 'car'] Output: '' Input: ['aa', 'a'] Output: 'a' ========================================= Many solutions for this problem exist (Divide and Conquer, Trie, etc) but this is the simplest and the fastest one. Use the first string as LCP and iterate the rest in each step compare it with another one. Time Complexity: O(N*A) , N = number of strings, A = average chars, or simplest notation O(S) = total number of chars Space Complexity: O(1) ''' ############ # Solution # ############ def longest_common_prefix(strs): n = len(strs) if n == 0: return '' lcp = strs[0] # instead of string manipulations, manipulate with the last common index lcp_idx = len(lcp) for i in range(1, n): lcp_idx = min(lcp_idx, len(strs[i])) for j in range(lcp_idx): if lcp[j] != strs[i][j]: lcp_idx = j break return lcp[:lcp_idx] ''' # if you like string manipulations, you can use this code # i don't like string manipulations in Python because they're immutable lcp = strs[0] for i in range(1, n): lcp = lcp[:len(strs[i])] for j in range(len(lcp)): if lcp[j] != strs[i][j]: lcp = lcp[:j] break return lcp ''' ########### # Testing # ########### # Test 1 # Correct result => 'fl' print(longest_common_prefix(['flower', 'flow', 'flight'])) # Test 2 # Correct result => '' print(longest_common_prefix(['dog', 'racecar', 'car'])) # Test 3 # Correct result => 'a' print(longest_common_prefix(['aa', 'a'])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |