2025-01-09:清除数字。用go语言,给定一个字符串s,你的任务是

架构师课程 2025-01-09 20:56:45

2025-01-09:清除数字。用go语言,给定一个字符串 s ,你的任务是执行以下操作,直到字符串中不再有数字字符:

删除第一个出现的数字字符,以及它左侧最近的非数字字符。

最终,你需要返回经过操作后剩下的字符串。

1 <= s.length <= 100。

s 只包含小写英文字母和数字字符。

输入保证所有数字都可以按以上操作被删除。

输入:s = "abc"。

输出:"abc"。

解释:

字符串中没有数字。

答案2025-01-09:

chatgpt[1]

题目来自leetcode3174。

大体步骤如下:

1.初始化一个空字节数组res来存储最终结果。

2.遍历输入字符串s中的每个字符c:

2.a.如果c是数字字符,则从res中删除最后一个字符。

2.b.如果c不是数字字符,则将c添加到res中。

3.返回res转换为字符串后的结果。

总体时间复杂度:

• 遍历输入字符串需要线性时间,即 O(n),其中 n 是输入字符串的长度。• 每次检查字符是否为数字,以及向字节数组中添加或删除元素都是常数时间操作。

总时间复杂度为 O(n)。

总体额外空间复杂度:

• 额外空间主要用于存储结果数组res,其大小取决于输入字符串中非数字字符的个数,最坏情况下为输入字符串的长度 n。• 因此,总的额外空间复杂度为 O(n)。Go完整代码如下:package mainimport ( "fmt" "unicode")func clearDigits(s string) string { var res []byte for _, c := range s { if unicode.IsDigit(c) { res = res[:len(res)-1] } else { res = append(res, byte(c)) } } return string(res)}func main() { s := "abc" result := clearDigits(s) fmt.Println(result)}

Rust完整代码如下:

fn clear_digits(s: &str) -> String { let mut res = String::new(); for c in s.chars() { if c.is_digit(10) { res.pop(); } else { res.push(c); } } res}fn main() { let s = "abc"; let result = clear_digits(s); println!("{}", result);}

C完整代码如下:

#include <stdio.h>#include <string.h>#include <stdlib.h> // Include stdlib.h for free functionchar *clearDigits(const char *s) { char res[100]; // Assuming a maximum length of 100 for the resulting string int resIndex = 0; for (int i = 0; s[i] != '\0'; i++) { char c = s[i]; if (c >= '0' && c <= '9') { if (resIndex > 0) { resIndex--; // Remove the last character } } else { res[resIndex] = c; resIndex++; } } res[resIndex] = '\0'; // Add null terminator to the end of the string char *result = strdup(res); // Using strdup to create a copy of the resulting string return result;}int main() { const char *s = "abc"; char *result = clearDigits(s); printf("%s\n", result); free(result); // Remember to free the allocated memory return 0;}

C++完整代码如下:

#include <iostream>#include <string>std::string clearDigits(const std::string& s) { std::string res; for (char c : s) { if (std::isdigit(c)) { res.pop_back(); } else { res.push_back(c); } } return res;}int main() { std::string s = "abc"; std::string result = clearDigits(s); std::cout << result << std::endl; return 0;}

Python完整代码如下:

# -*-coding:utf-8-*-def clear_digits(s): res = [] for c in s: if c.isdigit(): if res: res.pop() else: res.append(c) return ''.join(res)def main(): s = "abc" result = clear_digits(s) print(result)if __name__ == "__main__": main()

JavaScript完整代码如下:

function clearDigits(s) { let res = []; for (let i = 0; i < s.length; i++) { if (!isNaN(parseInt(s[i]))) { res.pop(); } else { res.push(s[i]); } } return res.join('');}let s = "abc";let result = clearDigits(s);console.log(result);

引用链接

[1] chatgpt: https://chatbotsplace.com/?rc=nnNWSCJ7EP

0 阅读:0