题目链接
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s
的形式给出。
不要给另外的数组分配额外的空间,你必须**原地修改输入数组**、使用 O(1) 的额外空间解决这一问题。
示例 1:
输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:
输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
提示:
1 <= s.length <= 10^5
s[i]
都是 ASCII 码表中的可打印字符Python:
#双指针
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
#使用库函数,不推荐
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
#栈
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
stack = []
for char in s:
stack.append(char)
for i in range(len(s)):
s[i] = stack.pop()
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n = len(s)
for i in range(n // 2):
s[i], s[n - i - 1] = s[n - i - 1], s[i]
#s = s[::-1] 创建一个新的列表对象,并将变量 s 指向这个新对象。
#s[:] = s[::-1] 在原地修改列表,将原始列表的元素替换为反转后的元素。
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s[:] = [s[i] for i in range(len(s) - 1, -1, -1)]
Go:
//双指针
func reverseString(s []byte) {
i, j := 0, len(s)-1
for i < j {
s[i], s[j] = s[j], s[i]
i++
j--
}
}
func reverseString(s []byte) {
for left, right := 0, len(s)-1; left < right; left++ {
s[left], s[right] = s[right], s[left]
right--
}
}
func reverseString(s []byte) {
l := len(s)
for i := 0; i < l/2; i++ {
s[i], s[l-i-1] = s[l-i-1], s[i]
}
}
题目链接
给定一个字符串 s
和一个整数 k
,从字符串开头算起,每计数至 2k
个字符,就反转这 2k
字符中的前 k
个字符。
k
个,则将剩余字符全部反转。2k
但大于或等于 k
个,则反转前 k
个字符,其余字符保持原样。示例 1:
输入:s = "abcdefg", k = 2
输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2
输出:"bacd"
提示:
1 <= s.length <= 10^4
s
仅由小写英文组成1 <= k <= 10^4
Python:
#官方解法
class Solution:
def reverseStr(self, s: str, k: int) -> str:
t = list(s)
for i in range(0, len(t), 2 * k):
t[i: i + k] = reversed(t[i: i + k])
return "".join(t)
class Solution:
def reverseStr(self, s: str, k: int) -> str:
b = list(s)
for i in range(0, len(b), 2 * k):
left = i
right = min(i + k - 1, len(b) - 1)
self.reverseString(b, left, right)
return "".join(b)
def reverseString(self, s: List[str], start: int, end: int) -> None:
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
class Solution:
def reverseStr(self, s: str, k: int) -> str:
l = len(s)
i = 0
chars = list(s)
while i <= l - 2 * k:
self.reverseString(chars, i, i + k - 1)
i += 2 * k
if l - i < k:
self.reverseString(chars, i, l - 1)
else:
self.reverseString(chars, i, i + k - 1)
return "".join(chars)
def reverseString(self, s: List[str], start: int, end: int) -> None:
i, j = start, end
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
Go:
//本人解法,可以借用反转字符串的函数,另外go语言中字符串是不可变的(immutable)。为了修复这个问题,你可以将字符串转换为可变的字节数组进行反转操作,然后再转回字符串。
func reverseStr(s string, k int) string {
l := len(s)
i := 0
chars := []byte(s)
for ; i <= l-2*k; i += 2 * k {
reverseString(chars[i : i+k])
}
if l-i < k {
reverseString(chars[i:l])
} else {
reverseString(chars[i : i+k])
}
return string(chars)
}
func reverseString(str []byte) {
i, j := 0, len(str)-1
for i < j {
str[i], str[j] = str[j], str[i]
i++
j--
}
}
func reverseStr(s string, k int) string {
b := []byte(s)
for i := 0; i < len(b); i += 2 * k {
left := i
right := i + k - 1
if right > len(b)-1 {
right = len(b) - 1
}
b = reverseString(b, left, right)
}
return string(b)
}
func reverseString(b []byte, i, j int) []byte {
for i < j {
b[i], b[j] = b[j], b[i]
i++
j--
}
return b
}
题目链接
给你一个字符串 s
,请你反转字符串中 单词 的顺序。
单词 是由非空格字符组成的字符串。s
中使用至少一个空格将字符串中的 单词 分隔开。
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
**注意:**输入字符串 s
中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = "the sky is blue"
输出:"blue is sky the"
示例 2:
输入:s = " hello world "
输出:"world hello"
解释:反转后的字符串中不能存在前导空格和尾随空格。
示例 3:
输入:s = "a good example"
输出:"example good a"
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
提示:
1 <= s.length <= 104
s
包含英文大小写字母、数字和空格 ' '
s
中 至少存在一个 单词Python:
#本人解法
class Solution:
def reverseWords(self, s: str) -> str:
i = 0
arr = []
l = len(s)
while i < l:
if s[i] != ' ':
left, right = i, i
while right < l:
if s[right] == ' ':
arr.append(s[left:right])
break
elif right == l - 1:
arr.append(s[left:right + 1])
i = right
right += 1
i += 1
l = len(arr)
result = arr[-1]
if l == 1:
return result
for i in range(l - 2, -1, -1):
result += " " + arr[i]
return result
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
s = s[::-1]
s = ' '.join(word[::-1] for word in s.split())
return s
class Solution:
def reverseWords(self, s: str) -> str:
words = s.split()
left, right = 0, len(words) - 1
while left < right:
words[left], words[right] = words[right], words[left]
left += 1
right -= 1
return " ".join(words)
Go:
//本人解法
func reverseWords(s string) (out string) {
i := 0
arr := make([]string, 0)
l := len(s)
for ; i < l; i++ {
if s[i] != ' ' {
left, right := i, i
for ; right < l; right++ {
if s[right] == ' ' {
arr = append(arr, s[left:right])
break
} else if right == l-1 {
arr = append(arr, s[left:right+1])
}
i = right
}
}
}
l = len(arr)
var builder strings.Builder
builder.WriteString(arr[len(arr)-1])
if l == 1 {
return builder.String()
}
for i = len(arr) - 2; i >= 0; i-- {
builder.WriteString(" " + arr[i])
}
return builder.String()
}
func reverseWords(s string) string {
b := []byte(s)
slow := 0
for i := 0; i < len(b); i++ {
if b[i] != ' ' {
if slow != 0 {
b[slow] = ' '
slow++
}
for i < len(b) && b[i] != ' ' {
b[slow] = b[i]
slow++
i++
}
}
}
b = b[0:slow]
reverse(b)
last := 0
for i := 0; i <= len(b); i++ {
if i == len(b) || b[i] == ' ' {
reverse(b[last:i])
last = i + 1
}
}
return string(b)
}
题目链接
给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
示例 1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 10^4
haystack
和 needle
仅由小写英文字符组成Python:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
for i in range(n - m + 1):
for j in range(m):
if haystack[i + j] != needle[j]:
break
else:
return i
return -1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(len(haystack) - len(needle) + 1):
if haystack[i : i + len(needle)] == needle:
return i
return -1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
try:
return haystack.index(needle)
except ValueError:
return -1
Go:
func strStr(haystack string, needle string) int {
for i := 0; i < len(haystack)-len(needle)+1; i++ {
if haystack[i:i+len(needle)] == needle {
return i
}
}
return -1
}
func strStr(haystack, needle string) int {
n, m := len(haystack), len(needle)
outer:
for i := 0; i+m <= n; i++ {
for j := range needle {
if haystack[i+j] != needle[j] {
continue outer
}
}
return i
}
return -1
}
题目链接
给定一个非空的字符串 s
,检查是否可以通过由它的一个子串重复多次构成。
示例 1:
输入: s = "abab"
输出: true
解释: 可由子串 "ab" 重复两次构成。
示例 2:
输入: s = "aba"
输出: false
示例 3:
输入: s = "abcabcabcabc"
输出: true
解释: 可由子串 "abc" 重复四次构成。 (或子串 "abcabc" 重复两次构成。)
提示:
1 <= s.length <= 10^4
s
由小写英文字母组成Python:
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
l = len(s)
for i in range(1, l // 2 + 1):
if l % i == 0:
tmp = s[:i]
j = i
while j <= l - i:
if s[j : j + i] != tmp:
break
j += i
if j == l:
return True
return False
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
for i in range(1, n // 2 + 1):
if n % i == 0:
match = True
for j in range(i, n):
if s[j] != s[j - i]:
match = False
break
if match:
return True
return False
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).find(s, 1) != len(s)
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
for i in range(1, n // 2 + 1):
if n % i == 0:
if all(s[j] == s[j - i] for j in range(i, n)):
return True
return False
Go:
//本人解法
func repeatedSubstringPattern(s string) bool {
l := len(s)
outer:
for i := 1; i <= l/2; i++ {
if l%i == 0 {
tmp := s[:i]
j := i
for ; j <= l-i; j += i {
if s[j:j+i] != tmp {
continue outer
}
}
if j == l {
return true
}
}
}
return false
}
func repeatedSubstringPattern(s string) bool {
n := len(s)
for i := 1; i * 2 <= n; i++ {
if n % i == 0 {
match := true
for j := i; j < n; j++ {
if s[j] != s[j - i] {
match = false
break
}
}
if match {
return true
}
}
}
return false
}