Java 9 ms easy to understand solution


  • 0
    H
    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            boolean reverse = true;
            int N = s.length();
            
            for(int i=0;i<N;i=i+k){
                int left = i;
                int right = (i+k<N)?(i+k):N;
                
                if(reverse) sb.append(reverseHelper(s.substring(left,right)));
                else sb.append(s.substring(left,right));
                    
                reverse=!reverse;
            }
            return sb.toString();
        }
        
        private String reverseHelper(String str){
            if(str==null||str.length()==0) return str;
            StringBuilder sb = new StringBuilder();
            for(int i=str.length()-1;i>=0;i--){
                sb.append(str.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.