6 lines java solution with O(n) runtime


  • 5
    P
        public String reverseStr(String s, int k) {
            StringBuilder res = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if (i % (2 * k) < k) res.insert(i - i % (2 * k), s.charAt(i));
                else res.append(s.charAt(i));
            }
            return res.toString();
        }
    

  • 1
    L
    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<s.length() ;i++ ){
                if((i/k)%2==0){
                    sb.insert(sb.length()-i%k,s.charAt(i));
                }else{
                    sb.append(s.charAt(i));
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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