zoukankan      html  css  js  c++  java
  • 剑指 Offer 58


    本题 题目链接

    题目描述


    我的题解

    方法一:使用库函数 s.substring()

    代码如下

        public String reverseLeftWords(String s, int n) {
            return s.substring(n, s.length()) + s.substring(0, n);
        }
    

    复杂度分析
    时间复杂度: O(N)
    空间复杂度: O(N)


    方法二:遍历

    思路分析

    • 若面试中不允许使用 切片函数,则可用此方法
    • 新建一个StringBuild字符串(不用String!消耗空间),记为res;
    • 先向res添加 index 为 n 至 length-1 的字符
    • 再向res添加 index 为 0 至 n-1 的字符串

    代码如下

    
        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();
        }
    
    

    复杂度分析
    时间复杂度: O(N)
    空间复杂度: O(N)


  • 相关阅读:
    canvas-8clip.html
    canvas-7globleCompositeOperation2.html
    canvas-7globleCompositeOperation.html
    canvas-7global.html
    canvas-6shadow.html
    canvas-6font.html
    A1036. Boys vs Girls
    A1006. Sign In and Sign Out
    A1011. World Cup Betting
    String 对象-->charAt() 方法
  • 原文地址:https://www.cnblogs.com/duduwy/p/13390564.html
Copyright © 2011-2022 走看看