docs: create 算法/字符串
This commit is contained in:
parent
c588e3de53
commit
cafc1229d5
99
算法/字符串.md
Normal file
99
算法/字符串.md
Normal file
@ -0,0 +1,99 @@
|
||||
---
|
||||
title: 字符串
|
||||
description:
|
||||
published: true
|
||||
date: 2024-03-21T11:16:17.692Z
|
||||
tags: 算法
|
||||
editor: markdown
|
||||
dateCreated: 2024-03-21T11:16:17.692Z
|
||||
---
|
||||
|
||||
# 反转字符串
|
||||
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
|
||||
|
||||
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
|
||||
|
||||
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
|
||||
|
||||
示例 1:
|
||||
输入:["h","e","l","l","o"]
|
||||
输出:["o","l","l","e","h"]
|
||||
|
||||
示例 2:
|
||||
输入:["H","a","n","n","a","h"]
|
||||
输出:["h","a","n","n","a","H"]
|
||||
```ts
|
||||
/**
|
||||
Do not return anything, modify s in-place instead.
|
||||
*/
|
||||
function reverseString(s: string[]): void {
|
||||
for (let i = 0, j = s.length - 1; i <= j; i++, j--) {
|
||||
let tmp = s[i];
|
||||
s[i] = s[j];
|
||||
s[j] = tmp;
|
||||
}
|
||||
};
|
||||
```
|
||||
# 反转字符串II
|
||||
给定一个字符串 s 和一个整数 k,从字符串开头算起, 每计数至 2k 个字符,就反转这 2k 个字符中的前 k 个字符。
|
||||
|
||||
如果剩余字符少于 k 个,则将剩余字符全部反转。
|
||||
|
||||
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
|
||||
|
||||
示例:
|
||||
|
||||
输入: s = "abcdefg", k = 2
|
||||
输出: "bacdfeg"
|
||||
```ts
|
||||
function reverseStr(s: string, k: number): string {
|
||||
const str = s?.split('');
|
||||
let flag = 0;
|
||||
function reverseString(i: number, j: number): void {
|
||||
for (; i <= j; i++, j--) {
|
||||
let tmp = str[i];
|
||||
str[i] = str[j];
|
||||
str[j] = tmp;
|
||||
}
|
||||
};
|
||||
while (str[flag]) {
|
||||
if (str[flag + k - 1]) {
|
||||
reverseString(flag, flag + k - 1)
|
||||
} else {
|
||||
reverseString(flag, str?.length - 1)
|
||||
}
|
||||
flag += 2 * k
|
||||
}
|
||||
return str.join('');
|
||||
};
|
||||
```
|
||||
# 替换数字
|
||||
给定一个字符串 s,它包含小写字母和数字字符,请编写一个函数,将字符串中的字母字符保持不变,而将每个数字字符替换为number。
|
||||
|
||||
例如,对于输入字符串 "a1b2c3",函数应该将其转换为 "anumberbnumbercnumber"。
|
||||
|
||||
对于输入字符串 "a5b",函数应该将其转换为 "anumberb"
|
||||
|
||||
输入:一个字符串 s,s 仅包含小写字母和数字字符。
|
||||
|
||||
输出:打印一个新的字符串,其中每个数字字符都被替换为了number
|
||||
|
||||
样例输入:a1b2c3
|
||||
|
||||
样例输出:anumberbnumbercnumber
|
||||
|
||||
数据范围:1 <= s.length < 10000。
|
||||
```ts
|
||||
const replaceNubmer=(s)=>{
|
||||
let arr = s.split('');
|
||||
let str = [];
|
||||
for(let i = 0;i<arr.length;i++){
|
||||
if(isNaN(arr[i])){
|
||||
str=[...str,arr[i]]
|
||||
}else{
|
||||
str=[...str,'number']
|
||||
}
|
||||
}
|
||||
return str.join('')
|
||||
}
|
||||
```
|
Loading…
Reference in New Issue
Block a user