1、解题思路
- 大小写转换:遍历字符串,逐个字符进行大小写转换。
- 单词分割与反转:使用栈来存储单词,利用栈的先进后出特性实现单词顺序反转。
- 处理结尾空格:检查原字符串末尾是否有空格,若有则保留在结果的首位。
2、代码实现
C++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
string trans(string s, int n) {
// write code here
if (n == 0) {
return s; // 空字符串直接返回
}
string res;
// 大小写转换
for (int i = 0; i < n; ++i) {
if (s[i] <= 'Z' && s[i] >= 'A') {
// res += s[i] - 'A' + 'a';
res += s[i] + 32; // 大写转小写
} else if (s[i] >= 'a' && s[i] <= 'z') {
res += s[i] - 32; // 小写转大写
} else {
res += s[i]; // 空格直接复制
}
}
stack<string> tmp;
// 单词分割与入栈
for (int i = 0; i < n; ++i) {
int j = i;
while (j < n && res[j] != ' ') {
++j; // 找到单词的结束位置
}
tmp.push(res.substr(i, j - i)); // 单词入栈
i = j; // 跳过已处理的单词
}
// 处理结尾空格的情况
if (s[n - 1] == ' ') {
res = " "; // 保留结尾空格
} else {
res = ""; // 否则清空
}
// 出栈拼接结果
while (!tmp.empty()) {
res += tmp.top(); // 栈顶单词加入结果
tmp.pop(); // 弹出栈顶
if (!tmp.empty()) res += " "; // 单词间加空格
}
return res;
}
};
Java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
public String trans (String s, int n) {
// write code here
if (n == 0) return s; // 空字符串直接返回
StringBuilder res = new StringBuilder();
// 大小写转换
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') {
res.append((char)(c - 'A' + 'a')); // 大写转小写
} else if (c >= 'a' && c <= 'z') {
res.append((char)(c - 'a' + 'A')); // 小写转大写
} else {
res.append(c); // 空格直接复制
}
}
Stack<String> temp = new Stack<>();
// 单词分割与入栈
for (int i = 0; i < n; i++) {
int j = i;
while (j < n && res.charAt(j) != ' ') j++; // 找到单词的结束位置
temp.push(res.substring(i, j)); // 单词入栈
i = j; // 跳过已处理的单词
}
// 处理结尾空格的情况
if (s.charAt(n - 1) == ' ') {
res = new StringBuilder(" "); // 保留结尾空格
} else {
res = new StringBuilder(); // 否则清空
}
// 出栈拼接结果
while (!temp.empty()) {
res.append(temp.pop()); // 栈顶单词加入结果
if (!temp.empty()) res.append(" "); // 单词间加空格
}
return res.toString();
}
}
Python
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @param n int整型
# @return string字符串
#
class Solution:
def trans(self , s: str, n: int) -> str:
# write code here
if n == 0:
return s # 空字符串直接返回
res = []
# 大小写转换
for c in s:
if 'A' <= c <= 'Z':
res.append(chr(ord(c) - ord('A') + ord('a'))) # 大写转小写
elif 'a' <= c <= 'z':
res.append(chr(ord(c) - ord('a') + ord('A'))) # 小写转大写
else:
res.append(c) # 空格直接复制
res = ''.join(res)
temp = []
i = 0
# 单词分割与入栈
while i < n:
j = i
while j < n and res[j] != ' ':
j += 1 # 找到单词的结束位置
temp.append(res[i:j]) # 单词入栈
i = j + 1 # 跳过已处理的单词和空格
# 处理结尾空格的情况
if s[-1] == ' ':
ans = ' ' # 保留结尾空格
else:
ans = '' # 否则清空
# 出栈拼接结果
while temp:
ans += temp.pop() # 栈顶单词加入结果
if temp:
ans += ' ' # 单词间加空格
return ans
3、复杂度分析
- 时间复杂度:O(n),其中 n 是字符串的长度。每个字符被处理两次(大小写转换和单词分割),单词反转的时间为 O(m),m 为单词数量,总体线性。
- 空间复杂度:O(n),用于存储转换后的字符串和栈,最坏情况下需要与原字符串相同的空间。