Share my Java Accepted Solution


  • 0
    M
    public String convert(String s, int k) {
        if(k<=0) return "";
        if(k==1 || s.length()<=k) return s;
        
        int interval = 2*k-2;
        int mid = interval;  // interval in process
        
        StringBuilder sb = new StringBuilder();
    
        for(int i=0;i<k && i< s.length();i++){
            for(int j=i;j<s.length();j=j+interval){
                sb.append(s.charAt(j));
                if(mid!=interval && mid!=0 && j+mid < s.length())
                    sb.append(s.charAt(j+mid));
            }
            mid-=2;
        }
        return sb.toString();
    }

  • 0
    C

    Excellent code!!! It's a little difficult to understand for me, however, your code is good enough! Short and efficient!!!


  • 0
    O

    why you write mid-=2 in this code?


Log in to reply
 

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