1. 程式人生 > >leetcode 6. ZigZag Conversion [java]

leetcode 6. ZigZag Conversion [java]

() row stringbu als ++ lean ringbuf == lse

自己寫的:

if(numRows == 1)   return s;
        int ll = s.length() / 2 + 1;
        Character tc[] = new Character[numRows* ll];
        int i = 0, j = 0;
        boolean down = true;
        for(int k = 0; k < s.length(); k++){
            tc[i* ll + j] = s.charAt(k);
            if(down){
                i++;
                if(i == numRows){
                    i -= 2;
                    j ++;
                    down = false;
                }
            }else{
                i--;
                j++;
                if(i == -1){
                    i = 1;
                    j --;
                    down = true;
                }
            }
        }
        String res = "";
        for(i=0;i < tc.length; i ++){
            if(tc[i] != null)
                res += tc[i]; 
        }
        return res;

參考於discuss:

char[] c = s.toCharArray();
        int len = c.length;
        StringBuffer[] sb = new StringBuffer[numRows];
        for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
        
        int i = 0;
        while(i < len){
            for (int idx = 0; idx < numRows&&i < len; idx ++)
                sb[idx].append(c[i++]);
            for (int idx = numRows -2; idx >= 1 && i < len; idx --)
                sb[idx].append(c[i++]);
        }
        for(int idx = 1;idx < sb.length; idx ++)
            sb[0].append(sb[idx]);
        return sb[0].toString();

leetcode 6. ZigZag Conversion [java]