23
文章讲解
力扣地址
C++
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1; // right 应该初始化为 s.size() - 1
while (left < right) {
swap(s[left], s[right]); // 直接交换 s[left] 和 s[right] 的值
left++;
right--;
}
}
};
Python
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
left=0
n = len(s)-1
right=n
while(left<right):
s[left], s[right] = s[right], s[left]
left+=1
right-=1
24
文章讲解
力扣地址
class Solution {
public:
string reverseStr(string s, int k) {
int n = s.size();
for (int i = 0; i < n; i += 2*k) {//每次处理2k个字符
int left = i;
int right = min(i + k - 1, n - 1);
while (left < right) {
swap(s[left], s[right]);
left++;
right--; // 更新 left 和 right 的值
}
}
return s;
}
};
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
s1=list(s)
left=0
right=0
n = len(s1)
for i in range(0,n,2*k):
left = i
right=min(i+k-1,n-1)
while left<right:
s1[left],s1[right]=s1[right],s1[left]
left+=1
right-=1
return "".join(s1)
25:
文章讲解
题目地址
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while(getline(cin, s)){
string result = ""; // 用于存储替换后的字符串
for(int i = 0; i < s.length(); i++){
if(isdigit(s[i])){ // 判断字符是否为数字
result += "number";
} else {
result += s[i];
}
}
cout << result << endl;
}
return 0;
}
判断是不是数字 isdigit(s[i)
while True:
try:
s = input()
s1 = list(s)
for i in range(len(s1)):
if s1[i]>='0' and s1[i]<='9':
s1[i]="number"
print(''.join(s1))
except:
break
这里注意 ’ '.join(s1)
26
文章讲解
题目地址
先翻转字符串再翻转每个单词
然后删除多余空格
reverse(s.begin(),s.end());
if(s[start]!=’ ‘)如果不是空格,说明新单词开始
if(idx!=0) s[idx++]=’ ’ 如果新单词不是第一个单词,加入前单词末尾空格
int end = start;
while(wend<n && s[end]!=‘’)
s[idx++]=s[end++]
通过一个while循环,找到完整的单词
reverse(s.begin()+idx-(end-start),s.begin()=idx);翻转单词
class Solution {
public:
string reverseWords(string s) {
// 反转整个字符串
reverse(s.begin(), s.end());
int n = s.size();
int idx = 0;
for (int start = 0; start < n; ++start) {
if (s[start] != ' ') {
// 填一个空白字符然后将idx移动到下一个单词的开头位置
if (idx != 0) s[idx++] = ' ';
// 循环遍历至单词的末尾
int end = start;
while (end < n && s[end] != ' ') s[idx++] = s[end++];
// 反转整个单词
reverse(s.begin() + idx - (end - start), s.begin() + idx);
// 更新start,去找下一个单词
start = end;
}
}
s.erase(s.begin() + idx, s.end());
return s;
}
};
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split()
words = words[::-1]
result = ' '.join(words)
return result