0% found this document useful (0 votes)
2 views2 pages

String Questions Python Codes

The document provides solutions to the top 10 string coding questions using Python. It includes functions for checking valid anagrams, palindromes, finding the longest common prefix, reversing strings and words, identifying the first unique character, and more. Each solution is presented with a concise code snippet for clarity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

String Questions Python Codes

The document provides solutions to the top 10 string coding questions using Python. It includes functions for checking valid anagrams, palindromes, finding the longest common prefix, reversing strings and words, identifying the first unique character, and more. Each solution is presented with a concise code snippet for clarity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Top 10 String Coding Questions with Python

Solutions
1. Valid Anagram

def isAnagram(s,t):
return sorted(s)==sorted(t)

2. Valid Palindrome

def isPalindrome(s):
s=''.join([Link]() for c in s if [Link]())
return s==s[::-1]

3. Longest Common Prefix

def longestCommonPrefix(strs):
prefix=strs[0]
for s in strs[1:]:
while not [Link](prefix):
prefix=prefix[:-1]
return prefix

4. Reverse String

def reverseString(s):
return s[::-1]

5. Reverse Words in a String

def reverseWords(s):
return ' '.join([Link]()[::-1])

6. First Unique Character

from collections import Counter


def firstUniqChar(s):
c=Counter(s)
for i,ch in enumerate(s):
if c[ch]==1:
return i
return -1
7. Longest Substring Without Repeating Characters

def lengthOfLongestSubstring(s):
seen={}
left=ans=0
for right,ch in enumerate(s):
if ch in seen and seen[ch]>=left:
left=seen[ch]+1
seen[ch]=right
ans=max(ans,right-left+1)
return ans

8. Group Anagrams

from collections import defaultdict


def groupAnagrams(strs):
d=defaultdict(list)
for s in strs:
d[''.join(sorted(s))].append(s)
return list([Link]())

9. Implement strStr()

def strStr(haystack,needle):
return [Link](needle)

10. Roman to Integer

def romanToInt(s):
val={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
ans=0
for i,ch in enumerate(s):
if i+1 ans-=val[ch]
else:
ans+=val[ch]
return ans

You might also like