[C++][Java] Clean Code


  • 18

    C++

    class Solution {
    public:
        /**
         * 0            k           2k          3k
         * |-----------|-----------|-----------|---
         * +--reverse--+           +--reverse--+
         */
        string reverseStr(string s, int k) {
            for (int left = 0; left < s.size(); left += 2 * k) {
                for (int i = left, j = min(left + k - 1, (int)s.size() - 1); i < j; i++, j--) {
                    swap(s[i], s[j]);
                }
            }
            return s;
        }
    };
    

    Java

    public class Solution {
        public String reverseStr(String s, int k) {
            char[] ca = s.toCharArray();
            for (int left = 0; left < ca.length; left += 2 * k) {
                for (int i = left, j = Math.min(left + k - 1, ca.length - 1); i < j; i++, j--) {
                    char tmp = ca[i];
                    ca[i] = ca[j];
                    ca[j] = tmp;
                }
            }
            return new String(ca);
        }
    }
    

  • 0
    B

    What is the time complexity of this solution? O(k.log(n))?


  • 0

    @bharath4 said in [C++][Java] Clean Code:

    What is the time complexity of this solution? O(k.log(n))?

    The time is O(n), n = string size.


  • 2
    M

    using while loop

        string reverseStr(string s, int k) {
            int i = 0, n = s.length();
            while(i<n) {
                int j = min(i+k-1, n-1);
                int nexti = j+k+1;
                while(i<j) swap(s[i++], s[j--]);
                i = nexti;
            }
            return s;
        }
    

  • 0
    C

    Using StringBuilder

    public String reverseStr(String s, int k) {
        StringBuilder str = new StringBuilder();
        for (int j = 0; j < s.length(); j += 2 * k) {
            for (int i = j; i < j + k && i < s.length(); i++) {
                str.insert(j, s.charAt(i));
            }
            for (int i = j + k; i < j + 2 * k && i < s.length(); i++) {
                str.append(s.charAt(i));
            }
        }
        return str.toString();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.