剑指offer一刷:字符串
剑指 Offer 05. 替换空格
难度:简单
方法一:遍历添加
class Solution {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(Character c : s.toCharArray())
{
if(c == ' ') res.append("%20");
else res.append(c);
}
return res.toString();
}
}
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/50c26h/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(N),空间复杂度:O(N)。
方法二:原地修改
在 C++ 语言中, string 被设计成「可变」的类型(参考资料),因此可以在不新建字符串的情况下实现原地修改。
因为不是 Java 代码实现的,这里就不贴代码了。
时间复杂度:O(N),空间复杂度:O(1)。
剑指 Offer 58 - II. 左旋转字符串
难度:简单
方法一:字符串切片
class Solution {
public String reverseLeftWords(String s, int n) {
return s.substring(n, s.length()) + s.substring(0, n);
}
}
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/58eckc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(N),空间复杂度:O(N)。
方法二:列表遍历拼接
class Solution {
public String reverseLeftWords(String s, int n) {
StringBuilder res = new StringBuilder();
for(int i = n; i < s.length(); i++)
res.append(s.charAt(i));
for(int i = 0; i < n; i++)
res.append(s.charAt(i));
return res.toString();
}
}
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/58eckc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(N),空间复杂度:O(N)。
方法三:字符串遍历拼接
class Solution {
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i = n; i < s.length(); i++)
res += s.charAt(i);
for(int i = 0; i < n; i++)
res += s.charAt(i);
return res;
}
}
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/58eckc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(N),空间复杂度:O(N)。
运行时间:一 < 二 < 三。
方法四:三次翻转(C++)
由于 C++ 中的字符串是 可变类型 ,因此可在原字符串上直接操作实现字符串旋转,实现 O(1) 的空间复杂度。
代码略。(左神书上有类似题,用Java代码实现三次翻转达到 O(1) 的空间复杂度)
时间复杂度:O(N),空间复杂度:O(1)。