四川建设企业网站,c++编程软件,数据线厂家东莞网站建设,c语言怎么做网页【问题描述】[中等] 【解答思路】
1. 字符串切片
应用字符串切片函数#xff0c;可方便实现左旋转字符串。 时间复杂度#xff1a;O(N) 空间复杂度#xff1a;O(N) public String reverseLeftWords(String s, int n) {return s.substring(n, s.length()) s.substring(0,…【问题描述】[中等] 【解答思路】
1. 字符串切片
应用字符串切片函数可方便实现左旋转字符串。 时间复杂度O(N) 空间复杂度O(N) public String reverseLeftWords(String s, int n) {return s.substring(n, s.length()) s.substring(0, n);}
2. 列表遍历拼接 时间复杂度O(N) 空间复杂度O(N)
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();}//求余运算 优化 public String reverseLeftWords(String s, int n) {StringBuilder res new StringBuilder();for(int i n; i n s.length(); i)res.append(s.charAt(i % s.length()));return res.toString();}
3. 字符串遍历拼接 时间复杂度O(N) 空间复杂度O(N) 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;}//取余运算优化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;}//求余运算 优化 【总结】
1.效率分析 2.字符串拼接
使用‘’进行字符串拼接时Java实际上是通过new出一个StringBuilder对象然后进行append操作最后通过toString方法返回String对象完成的会造成内存资源的额外浪费。
所以如果在循环体中字符串的连接方式推荐使用StringBuilder的append方法进行扩展而不要使用‘’。
不是在循环体中的话可以使用‘’代码更加简洁和可读如方法一的代码。
3.字符串拼接题目速度 切割函数列表StringBuilder 字符串String
转载链接https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/solution/mian-shi-ti-58-ii-zuo-xuan-zhuan-zi-fu-chuan-qie-p/