Leetcode344.反转字符串
题目链接:344. 反转字符串
C++:
class Solution {
public:
void reverseString(vector<char>& s) {
for(int i=0, j=s.size()-1; i < s.size()/2; i++, j--)
swap(s[i], s[j]);
}
};
Python:
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
j = len(s) - 1
for i in range(len(s) // 2):
s[i], s[j] = s[j], s[i]
j -= 1
Leetcode541. 反转字符串II
题目链接:541. 反转字符串 II
C++:
class Solution {
public:
string reverseStr(string s, int k) {
for(int i=0; i < s.size(); i += (2*k))
{
if(i + k < s.size())
reverse(s.begin()+i, s.begin()+i+k);
else
reverse(s.begin()+i, s.end());
}
return s;
}
};
Python:
range()函数:
(1)用法:range(start, stop[, step])
python语法:
(1)函数需要先定义后调用
' '.join()用法:
(1)str.join(item)
(2)' '.join(item)含义:将字符串item中的每个成员以空格' '分开再拼接成一个字符串
(3)','.join(item)含义:将字符串item中的每个成员以逗号','分开再拼接成一个字符串
class Solution:
def reverse(self, start, end, s):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
def reverseStr(self, s: str, k: int) -> str:
l = len(s)
n = l // (2*k)
res = list(s)
if l % (2*k) <= k:
left = 0
right = k-1
for i in range(n):
self.reverse(left, right, res)
left += (2*k)
right += (2*k)
self.reverse(left, l-1, res)
else:
left = 0
right = k-1
for i in range(n):
self.reverse(left, right, res)
left += (2*k)
right += (2*k)
self.reverse(left, right, res)
return ''.join(res)
卡码网:54.替换数字
题目链接:54. 替换数字
C++:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string s;
while(cin >> s)
{
int s_oldindex = s.size() - 1;
int count = 0;
for(int i=0; i < s.size(); i++)
{
if(s[i] >= '0' && s[i] <= '9')
count++;
}
s.resize(s.size() + 5*count);
int s_newindex = s.size() - 1;
while(s_oldindex >= 0)
{
if(s[s_oldindex] >= '0' && s[s_oldindex] <= '9')
{
s[s_newindex--] = 'r';
s[s_newindex--] = 'e';
s[s_newindex--] = 'b';
s[s_newindex--] = 'm';
s[s_newindex--] = 'u';
s[s_newindex--] = 'n';
}
else
s[s_newindex--] = s[s_oldindex];
s_oldindex--;
}
cout << s << endl;
}
}
Python:
class Solution:
def replace_number(self, s:str)->str:
res = list(s)
for i in range(len(s)):
if res[i] in ['1','2','3','4','5','6','7','8','9']:
res[i] = 'number'
return ''.join(res)
sol = Solution()
s = input()
result = sol.replace_number(s)
print(result)