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/reverse_vowels.py at master · CROXX-Code/coding-problems Expand file tree/ Copy pathreverse_vowels.pyMore file actions 75 lines (57 loc) · 1.93 KB / Copy pathreverse_vowels.pyFile metadata and controls75 lines (57 loc) · 1.93 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 ''' Reverse Vowels Given a text string, create and return a new string constructed by finding all its vowels (for simplicity, in this problem vowels are the letters in the string 'aeiouAEIOU') and reversing their order, while keeping all non-vowel characters exactly as they were in their original positions. Input: 'Hello world' Output: 'Hollo werld' ========================================= Simple solution, find a vowel from left and swap it with a vowel from right. In Python, the string manipulation operations are too slow (string is immutable), because of that we need to convert the string into array. In C/C++, the Space complexity will be O(1) (because the strings are just arrays with chars). Time Complexity: O(N) Space Complexity: O(N) ''' ############ # Solution # ############ def reverse_vowels(sentence): arr = [c for c in sentence] # or just arr = list(sentence) vowels = { 'a': True, 'A': True, 'e': True, 'E': True, 'i': True, 'I': True, 'o': True, 'O': True, 'u': True, 'U': True } left = 0 right = len(arr) - 1 while True: # find a vowel from left while left < right: if arr[left] in vowels: break left += 1 # find a vowel from right while left < right: if arr[right] in vowels: break right -= 1 if left >= right: # in this case, there are only 1 or 0 vowels # so this is the end of the algorithm, no need from more reversing break # swap the vowels arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 return ''.join(arr) ########### # Testing # ########### # Test 1 # Correct result => 'ubcdofghijklmnepqrstavwxyz' print(reverse_vowels('abcdefghijklmnopqrstuvwxyz')) # Test 2 # Correct result => 'Hollo werld' print(reverse_vowels('Hello world')) |
| 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. |