Leetcode
Leetcode
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.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105
code:
class Solution:
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
j += 1
i += 1
return len(t) – j
#Longest palindrome
class Solution:
def longestPalindrome(self, s: str) -> int:
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
length = 0
odd_count = 0
for count in char_count.values():
if count % 2 == 0:
length += count
else:
length += count - 1
odd_count += 1
if odd_count > 0:
length += 1
return length
Given a string array words, return an array of all characters that show up in all
strings within the words (including duplicates). You may return the answer in any
order.
Example 1:
Input: words = ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: words = ["cool","lock","cook"]
Output: ["c","o"]
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists of lowercase English letters.
Code:
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
if not words:
return []
common_chars = set(words[0])
for word in words[1:]:
common_chars &= set(word)
result = []
for char in common_chars:
count = min(word.count(char) for word in words)
result.extend([char] * count)
return result