String Problems

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Backspace String Compare - LC

# is backspace char, see if two strings are equal Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". naive approach -use a stack. N/N Optimal - iterate over string backwards, skipping chars after '#' . Use zip_longest and generator function to get constant space N/1

Boyer Moore Horspool Algorithm - finding substring in str

-Python uses a variant of BMH -still O(mn) worst case Ex : text = 'trusthardtoothbrushes' pattern = 'tooth' 1) construct a bad match or skip table that goes through each character in the pattern and calculates a value ==> (length - idx - 1) Skip Table ------------------ Letter ==> Value T = 1 O = 2 H = 5 (set as length if not already defined, otherwise used existing val) * = 5 (any other letter - just input the l) 2) Start at the left of text, but the right char of pattern -if there's a mismatch, look up the text mismatch char in the skip table and skip ahead by that value -If the mismatch char isn't in the skip table, use the first text char in the match (from the right) to determine skip value https://www.youtube.com/watch?v=PHXAOKQk2dw

LC #387 - First Unique Char in String

-find the first char that's unique in a string, and return it's index (or -1 if no unique) s = "leetcode" return 0. s = "loveleetcode", return 2. 1) Brute Force - n/n -store char and index of char that only appear once in a dictionary. At the end return the min of d.values() 2) Optimal - n / 1 -loop over letter, for each letter if the s.count() ==1, add it to our index. at the end return the min index

Longest Common Prefix - LC #14

-find the longest common prefix among string Input: ["flower","flow","flight"] Output: "fl" use zip(*input) an

KMP (Knuth-Moriss-Pratt) Algorithm - finding substring in string

-preprocess a table with the length of a suffix and prefix match to have -start matching from left to right, on

516. Longest Palindromic Subsequence

.

LC #7 - Reverse Integer

123 ==> 321 -123 ==> -321 -only in 32-bit signed int range [-2^31, 2^31-1] 1) Naive - O(d) / O(d) solution -Mark if it's negative. Reverse the string and turn to int. If the abs(answer) is overflow, return 0. Otherwise return the correctly signed ans 2) Optimal - d / 1 or log(x) / 1 -Reverse with math rather than converting to a string while n>0: ans = (ans*10) + (n%10) n = n//10

ASCII vs Unicode

ASCII - 7 bits => 0...127 Unicode => 0 ... 2^21 -Unicode can have different encodings UTF-8 (8 bit), UTF-16, UTF-32 -Extend ASCII - 8 bits

LC #953 - Verifying an Alien Dictionary

Check if list of strings are in lexicographical order based on a modified alphabet Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false 1) O(w*c) / 1 (where w is num of words, and c is number of char in max char) -store alien alphabet in dictionary representing each letter's index -loop through each word - set a curr and a prev -loop to the point where the characters of two strings differ (j) - If the char at this index j are the same, check for (apple vs app) rule , if app is curr, return False -if the char are different -if order_index[prev[j]] > order_index[curr[j]] - return False

CTCI - String Rotation

Determine if a string is a rotation of another string ('waterbottle', 'erbottlewat', True), ('foo', 'bar', False), ('foo', 'foofoo', False),

5. Longest Palindromic Substring

Find longest palindromic substring .Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Input: "cbbd" Output: "bb" 1) naive - n^3 / n def ispal: return z==z[::-1] for i in range(len(s)): for j in range(i+1, len(s)+1): if substring from i to j is a palindrome: -set new longest = ( len(substr), [i,j]) - return longest substring from i to j 2) expand around center - n^2 / 1 - for each index in s: -call helper function to expand left and right until we reach the end -if this expanded string is bigger than current answer, set new answer -need to call helper for odd helper(s, i,i) and even==> helper(s,i,i+1) # expand around center - N^2 / N def helper(s,l,r): while l>=0 and r< len(s) and s[l]==s[r]: l -=1; r += 1 return s[l+1: r] res = '' for i in range(len(s)): tmp = helper(s, i, i) #odd case if len(tmp) > len(res): res = tmp tmp = helper(s, i, i+1) if len(tmp) > len(res): res = tmp return res

266. Palindrome Permutation

Given a string, determine if a permutation of the string could form a palindrome. Input: "code" Output: false Input: "aab" Output: true Input: "carerac" Output: true 1) Naive - N/N - loop through collections.Counter(s) - count number of even freq and number of odd freq -if oddCount is 0 or 1 : simply return True since we know a palindrome can have at most 1 oddCount - return False otherwise - since we have all even counts 2) ASCII array trick for constant space ==> N/ 1 - create a maps array initialized to 0 => [0] * 128 - loop thru string, incrementing each maps location - start a count at 0, loop through maps, find the number of oddCounts (using modulo) -return oddcounts <= 1 (odd count must be less than or equal to 1)

LC #1002 - Find Common Characters

Given array A of strings - return a list of all characters that show up in all strings - including duplicates Input: ["bella","label","roller"] Output: ["e","l","l"] Input: ["cool","lock","cook"] Output: ["c","o"] 1) Counter & n*c / c -where c is avg # of char -Simply and the count of chars from collections import Counter res = Counter(A[0]) for word in A: res &= Counter(word) return list(res.elements())

LC #242 - Valid Anagram

Given two strings s and t , write a function to determine if t is an anagram of s. You may assume the string contains only lowercase alphabets. Input: s = "anagram", t = "nagaram" Output: true 1) Brute force - n / n -create a counter of each and see if they're the same sc = Counter(s) tc = Counter(t) return sc == tc 2) sort - nlgn / 1 or nlgn/n (constant space if we use heapsort) return sorted(s) == sorted(t) 2)Optimal - n / 1 -or (s+t) / 1 -create a dictionary of lowercase letters a-z import string d = { ch: 0 for ch in string.ascii_lowercase} c = { ch: 0 for ch in string.ascii_lowercase} for ch in s: d[ch] += 1 for ch in t: c[ch]+=1 return d==c

CTCI - One Away

Given two strings, check if they are one or zero edits away pale, ple => True pale, bale => True Pale, bake => False -if their the same length zip them and check if error count is more than one

Add Binary strings #67

Input: a = "1010", b = "1011" Output: "10101" 1) Brute Force - add reversed strings using zip_longest(a,b,fillvalue='0') . N^2/N 2) Optimal - bin(eval('0b' + a) + eval('0b' + b))[2:]

CTCI - Determine if a string has all unique characters

N/1 optimal solution is (if it's ascii) create a list [0...127] to represent characters we've seen - this is a constant space solution -if it's a unicode string - create a list of [0...2^21]

LC #28 - strstr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. ------------------------------------------ Input: haystack = "hello", needle = "ll" Output: 2 -------------------------------------- 1) optimal / easy - O(mn) - find gets *return haystack.find(needle)* # O(mn) - for each char in haystack: if there's a match: for each char in needle: compare it to char in haystack

CTCI - URLify

URLify(string, length) -replace all spaces in string with '%20' -one pointer at the back = len(string) -other point loops from reversed(range(length))

CTCI - Rotate 2d matrix

[1, 2, 3], [4, 5, 6], [7, 8, 9] becomes => [7, 4, 1] [8, 5, 2] [9, 6, 3] -reverse the list -for i in range(n) for j in range(i, n) l[i][j], l[j][i] = l[j][i], j[i][j] #swap 1 liner: l[:] = zip(*l[::-1])

CTCI - Zero Matrix

[1,2,3], [4,0,5], [6,7,8] => [1,0,3] [0,0,0] [6,0,8] (m rows and n col) 1)Brute Force - loop over rows and columns, if we find a 0, set the entire row to 0, and add the colsToSet to a set(). Finally loop through colsToSet and set all the rows in that column to 0. => m*n^2 / n 2)Optimal - loop through all rows and columns, if we encounter a 0 , mark the first item in the row and first item in the column to 0. Loop through each row, if it has a zero set entire row to 0. Loop through each col, if it has a 0, set entire row to 0. => m*n / 1

CTCI - String Compress

aabcccd ==> a2bc3d -if len(set(s)) == len(s) - then just return s -else loop through the array using two pointers, and storing count (count starts at 1)

CTCI - Palindrome Permutation

determine if a random string can be re-aranged to form a palindrome -a palindrome generally has an even count of each characters, and is allowed one odd count -run a collections.Counter(string) and check that there is at most 1 character that has an odd count/frequency N/1


Ensembles d'études connexes

Chapter 2: Encounter and Conquest

View Set

hair, skin & nails health assessment

View Set

Essentials of Statistics for the Behavioral Sciences Ch.3

View Set

Agl sociology quiz 2 (multiple choice)

View Set

Normal Balance: Debit or Credit?

View Set

Introductory Microeconomics Chapter 7 Quiz

View Set

Psych Midterm Evolve Quizes (2-6 (Not as important))

View Set

COMM 101 FINAL Q #13 What is facework in communication studies? According to Dr. Ishani Mukherjee and Dr. Maggie Griffith Williams, how do the Hmong view forgiveness and facework? Describe 1 of Mukherjee and Williams' examples of forgiveness and facework

View Set