Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if a string can be converted to another string by replacing vowels and consonants in Python
Sometimes we need to check if one string can be transformed into another by replacing characters with specific rules. In this problem, we can only replace vowels with other vowels and consonants with other consonants.
The transformation rules are:
- A vowel (a, e, i, o, u) can only be replaced with another vowel
- A consonant can only be replaced with another consonant
- Both strings must have the same length
Example
If we have s = "udpmva" and t = "itmmve", we can transform:
- u (vowel) ? i (vowel) ?
- d (consonant) ? t (consonant) ?
- p (consonant) ? m (consonant) ?
- m (consonant) ? m (consonant) ?
- v (consonant) ? v (consonant) ?
- a (vowel) ? e (vowel) ?
Solution Approach
The algorithm works as follows:
- Check if both strings have the same length
- For each character position, verify that both characters are either vowels or both are consonants
- If any position violates this rule, return False
- If all positions follow the rule, return True
Implementation
def is_vowel(x):
return x.lower() in ['a', 'e', 'i', 'o', 'u']
def can_transform(s, t):
# Check if lengths are equal
if len(s) != len(t):
return False
# Check each character position
for i in range(len(s)):
s_is_vowel = is_vowel(s[i])
t_is_vowel = is_vowel(t[i])
# Both must be vowels or both must be consonants
if s_is_vowel != t_is_vowel:
return False
return True
# Test the function
s = "udpmva"
t = "itmmve"
result = can_transform(s, t)
print(f"Can '{s}' be transformed to '{t}'? {result}")
Can 'udpmva' be transformed to 'itmmve'? True
Testing Different Cases
def is_vowel(x):
return x.lower() in ['a', 'e', 'i', 'o', 'u']
def can_transform(s, t):
if len(s) != len(t):
return False
for i in range(len(s)):
if is_vowel(s[i]) != is_vowel(t[i]):
return False
return True
# Test cases
test_cases = [
("udpmva", "itmmve"), # True - valid transformation
("hello", "world"), # False - vowel to consonant
("aeiou", "ioeua"), # True - all vowels
("bcdfg", "mnpqr"), # True - all consonants
("abc", "abcd") # False - different lengths
]
for s, t in test_cases:
result = can_transform(s, t)
print(f"'{s}' ? '{t}': {result}")
'udpmva' ? 'itmmve': True 'hello' ? 'world': False 'aeiou' ? 'ioeua': True 'bcdfg' ? 'mnpqr': True 'abc' ? 'abcd': False
Time and Space Complexity
- Time Complexity: O(n), where n is the length of the strings
- Space Complexity: O(1), using only constant extra space
Conclusion
This algorithm checks string transformation by ensuring vowels can only replace vowels and consonants can only replace consonants. The solution is efficient with linear time complexity and handles edge cases like different string lengths.
Advertisements
