面试题答案
一键面试实现思路
- 从字符串的开头开始遍历,找到第一个既不是空白字符也不是
'-'
的字符位置。 - 从字符串的末尾开始遍历,找到第一个既不是空白字符也不是
'-'
的字符位置。 - 提取这两个位置之间的子字符串,即为修剪后的结果。
关键代码点
- 遍历开头:使用循环,检查每个字符是否为空白字符或
'-'
,直到找到第一个有效字符。 - 遍历末尾:类似地,从字符串末尾反向遍历,找到最后一个有效字符。
- 提取子字符串:根据找到的开头和末尾位置,提取子字符串。
示例代码(JavaScript)
function trimSpecial(s) {
let start = 0;
while (start < s.length && (s[start] === ' ' || s[start] === '\t' || s[start] === '\n' || s[start] === '-')) {
start++;
}
let end = s.length - 1;
while (end >= 0 && (s[end] === ' ' || s[end] === '\t' || s[end] === '\n' || s[end] === '-')) {
end--;
}
return s.substring(start, end + 1);
}
你可以使用如下方式调用函数:
let s = "- hello - world -";
console.log(trimSpecial(s));
示例代码(Python)
def trimSpecial(s):
start = 0
while start < len(s) and (s[start].isspace() or s[start] == '-'):
start += 1
end = len(s) - 1
while end >= 0 and (s[end].isspace() or s[end] == '-'):
end -= 1
return s[start:end + 1]
你可以使用如下方式调用函数:
s = "- hello - world -"
print(trimSpecial(s))