String¶
Table of Contents¶
- 344. Reverse String (Easy)
- 541. Reverse String II (Easy)
- 151. Reverse Words in a String (Medium)
- 58. Length of Last Word (Easy)
- 844. Backspace String Compare (Easy)
- 2185. Counting Words With a Given Prefix (Easy)
- 2000. Reverse Prefix of Word (Easy)
344. Reverse String¶
from typing import List
def reverseString(s: List[str]) -> 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 += 1
right -= 1
s = ["h", "e", "l", "l", "o"]
reverseString(s)
print(s) # ['o', 'l', 'l', 'e', 'h']
#include <cassert>
#include <vector>
using namespace std;
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0, right = s.size() - 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
}
};
int main() {
Solution solution;
vector<char> s = {'h', 'e', 'l', 'l', 'o'};
solution.reverseString(s);
assert(s == vector<char>({'o', 'l', 'l', 'e', 'h'}));
return 0;
}
541. Reverse String II¶
def reverseStr(s: str, k: int) -> str:
def reverse_substring(text):
left, right = 0, len(text) - 1
while left < right:
text[left], text[right] = text[right], text[left]
left += 1
right -= 1
return text
result = list(s)
for i in range(0, len(s), 2 * k):
result[i : i + k] = reverse_substring(result[i : i + k])
return "".join(result)
s = "abcdefg"
k = 2
print(reverseStr(s, k)) # "bacdfeg"
151. Reverse Words in a String¶
58. Length of Last Word¶
844. Backspace String Compare¶
2185. Counting Words With a Given Prefix¶
from typing import List
# 1
def prefixCount1(words: List[str], pref: str) -> int:
count = 0
for word in words:
if word.startswith(pref):
count += 1
return count
# 2
def prefixCount2(words: List[str], pref: str) -> int:
count = 0
for word in words:
n = len(pref)
if len(word) < n:
continue
if word[:n] == pref:
count += 1
return count
words = ["pay", "attention", "practice", "attend"]
pref = "at"
print(prefixCount1(words, pref)) # 2
print(prefixCount2(words, pref)) # 2
2000. Reverse Prefix of Word¶
def reversePrefix(word: str, ch: str) -> str:
if ch not in word:
return word
wordList = list(word)
left, right = 0, 0
for i in range(len(wordList)):
if wordList[i] == ch:
right = i
break
while left < right:
wordList[left], wordList[right] = wordList[right], wordList[left]
left += 1
right -= 1
return "".join(wordList)
word = "abcdefd"
ch = "d"
print(reversePrefix(word, ch)) # "dcbaefd"