Solution by Java(98%+)


  • 0
    S
     public String convert(String s, int numRows) {
            if(numRows==1){  
                return s;
            }
            char[] chars = s.toCharArray();
            int length = chars.length;
            //the interval between every two characters in the first line
            int interval = 1+(numRows-2<<1); 
            //use char array to buffer the sorted characters
            char[] resultTemp = new char[length];
            //the cursor for first line
            int globalCursor = 0;
            //the cursor for the last stored character's index 
            int reultCursor = 0;
            //the offset of an interval
            int cursor = 1;
            //in an interval the next line's two characters's index 
            //left = globalCursor+cursor  right=globalCursor+interval+1-cursor
            int left = 0;
            int right = 0;
            //get the first line's characters
            while(globalCursor<length){
                resultTemp[reultCursor++] = chars[globalCursor];
                globalCursor+=interval+1;
            }
            globalCursor = 0;
            for(;cursor<=((interval+1)>>1);cursor++,globalCursor = 0){
                while((left=globalCursor+cursor)<length){
                    resultTemp[reultCursor++] = chars[left];
                    globalCursor+=interval+1;
                    if((right=globalCursor-cursor)<length&&left!=right){
                        resultTemp[reultCursor++] = chars[right];
                    }
                }
            }
            return new String(resultTemp);
        }
    

Log in to reply
 

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