Leetcode-006-Z transform shaped

The idea is to solve this problem the finite state machine FSM, there are two states when building arrangement, either up or down, how inter-state switch it? Upward in the first row and then the turned down, the last row in the downward and then upward to get rid of the head. The idea is this.

class Solution {
    public String convert(String s, int numRows) {

        if(s.length()<2||numRows<2) return s;

        List<StringBuilder> demo = new ArrayList<>();

        for(int i=0;i<Math.min(s.length(), numRows);i++){
            demo.add(new StringBuilder());
        }

        int down=1;
        int row=0;

        for(char c:s.toCharArray()){
            demo.get(row).append(c);
            if((row==0&&down==-1)||(row==numRows-1&&down==1)){
                down*=-1;
            }
            if(down==1){
                row++;
            }else{
                row--;
            }
        }

        StringBuilder returnStr = new StringBuilder();

        for(StringBuilder sb:demo){
            returnStr.append(sb);
        }
        return returnStr.toString();


    }
}
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        
        if(numRows<2):
            return s

        demo = [[] for i in range(min(len(s), numRows))]
        down = 1
        row = 0

        for c in s:
            demo[row].append(c)

            if((row==0 and down==-1)or(row==numRows-1 and down==1)):
                down*=-1
            if down==1:
                row+=1
            else:
                row-=1
        result = ''
        for i in demo:
            for j in i:
                result+=j
        return result

 

Guess you like

Origin www.cnblogs.com/huangzengrui/p/12345332.html