String
- This is created because there are so many interesting string problems that do not really fit into any other categories, just straight up understanding the problem and implement/handle edge cases
https://leetcode.com/problems/group-shifted-strings
def groupStrings(self, strings: List[str]) -> List[List[str]]:
# any 2 strings that have the same length and same character offset between then should be in the same group
def getCharDiff(s):
if len(s) == 1:
return []
diffs = []
for i in range(1, len(s)):
diff = (ord(s[i]) - ord(s[i - 1])) % 26
diffs.append(diff)
return diffs
diffsMap = collections.defaultdict(list)
for s in strings:
diffs = getCharDiff(s)
diffsMap[tuple(diffs)].append(s)
return list(diffsMap.values())
https://leetcode.com/problems/valid-number
- Just if/else
- Keep track of defining variables/state that let us know immediately if it is invalid
def isNumber(self, s: str) -> bool:
seenDot = False
seenDigit = False
seenExp = False
for i in range(len(s)):
if s[i].isdigit():
seenDigit = True
elif s[i] == ".":
if seenDot or seenExp:
return False
seenDot = True
elif s[i] in "+-":
if i != 0 and s[i - 1] not in "Ee":
return False
seenDigit = False
elif s[i] in "Ee":
if seenExp or not seenDigit:
return False
seenExp = True
seenDigit = False
else:
return False
return seenDigit