Skip to the content.

6. Z字形变换

我的解法:

class Solution {
    public String convert(String s, int numRows) {
        if(numRows == 1)
        {
            return s;
        }
        int total = numRows * 2 - 2;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < numRows; i ++)
        {
            int num1 = total - 2 * i;
            int num2 = total - num1;
            int label = 1;
            int index = i;
            int a = 0;
            while(true)
            {
                int number = index;
                if(a == 0)
                {
                    number = index;
                    a ++;
                }
                else
                {
                    if(label == 1)
                    {
                    	label = -1;
                        if(i == numRows - 1)
                        {
                            continue;
                        }
                        number += num1;
                        
                    }
                    else if(label == -1)
                    {
                    	label = 1;
                        if(i == 0)
                        {
                            continue;
                        }
                        number += num2;
                        
                    }    
                }
                if(number >= s.length())
                {
                    break;
                }
                sb.append(s.charAt(number));
                index = number;
            }
        }
        return sb.toString();
    }
}