strings Flashcards
- Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
def findAnagram(strings):
#example string Input: strs = ["eat","tea","tan","ate","nat","bat"] #Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
anagram = {} for words in strings: sortedword = ''.join(sorted(words)) if sortedword in anagram: anagram[sortedword].append(words) else: anagram[sortedword] = [words] return list(anagram.values())
strings = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
print(findAnagram(strings))
Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
- Word Pattern
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Input: pattern = “abba”, s = “dog cat cat dog”
Output: true
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: splitA = s.split() return list(map(pattern.index, pattern)) == list(map(splitA.index, splitA))
- Reverse String solution 1
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """
left, right = 0, len(s)- 1 while left < right: s[left], s[right] = s[right], s[left] left, right = left + 1, right - 1 return string
- First Unique Character in a String
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ count = collections.Counter(s) for idx, char in enumerate(s): if count[char] == 1: return idx
return -1
- To Lower Case
Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.
class Solution(object): def toLowerCase(self, s): """ :type s: str :rtype: str """
return s.lower()
solution 2: def toLowerCase(self, s): """ :type s: str :rtype: str """
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lower = "abcdefghijklmnopqrstuvwxyz" h = dict(zip(upper, lower)) return ''.join([h[x] if x in h else x for x in s])
- Maximum Number of Balloons
Given a string text, you want to use the characters of text to form as many instances of the word “balloon” as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
example
text = “nlaebolko”
from collections import Counter
class Solution: def maxNumberOfBalloons(self, text: str) -> int: c = Counter(text) return min(c['a'], c['b'], c['l']//2, c['o']//2, c['n'])
How To Convert Python String To Array?
example string = ‘hello’
example1
str = “MillieB11”
arr = list(str)
print(arr)
output = [‘M’, ‘i’, ‘l’, ‘l’, ‘i’, ‘e’, ‘B’, ‘1’, ‘1’]
example 2
str = “Millie Bobby Brown is Enola Holmes”
arr = str.split()
print(arr)
[‘Millie’, ‘Bobby’, ‘Brown’, ‘is’, ‘Enola’, ‘Holmes’]
How to sort a string without separating the characters?
example1
sortedwords = ‘‘.join(sorted(‘word’)
print sorted words —> dorw
example two:
print(sorted(‘aet’)) —> [‘a’, ‘e’, ‘t’]
How to stow dictionary keys and their count of a string?
using collections.Counter()
from collections import Counter
example
s = ‘leetcode’
count = Counter(s)
result –> Counter({‘e’: 3, ‘l’: 1, ‘t’: 1, ‘c’: 1, ‘o’: 1, ‘d’: 1})
Palindrome check (algoexpert)
write a function that takes in a non-empty string that returns a boolean representing whether a string is a palindrome.
a palindrome is referred to as a string that is written the same forward as backward
eg. string = ‘abcdcba’
def isPalindrome(string): # Write your code here. return (string == string[::-1])
what does this % operator sign mean in python?
Modulus - remainder of the division of left operand by the right
what does this // operator sign mean in python?
Floor division - division that results into whole number adjusted to the left in the number line
Caesar Cipher Encryptor (Algoexpert)
Given a non-empty string of lowercase letters and a non-negative integer representing a key, write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet, where k is the key.
def caesarCipherEncryptor(string, key): # Write your code here. #i want to use the 26 scale.so i will change everything to upper string = string.upper()
key = key%26
#let's keep track of the char and their corresponding numbers #let's also keep track of the new string newString = [] for char in string: numberChar = ord(char) #let's make the shift in the number newNumber = numberChar + key if newNumber <= 90: newChar = chr(newNumber) newString.append(newChar) else: newChar = chr(newNumber+64-90) newString.append(newChar) return ''.join(newString).lower()
How do you change a string to upper case?
string.upper()
How do you change a string to lower case?
string.lower()