Algorithm-zigzag transformation

Algorithm-zigzag transformation

1. Z-shaped transformation

6. Zigzag transformation

	将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
	
	比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
	
	L   C   I   R
	E T O E S I I G
	E   D   H   N
	之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
	
	请你实现这个将字符串进行指定行数变换的函数:
	
	string convert(string s, int numRows);
	示例 1:
	
	输入: s = "LEETCODEISHIRING", numRows = 3
	输出: "LCIRETOESIIGEDHN"
	示例 2:
	
	输入: s = "LEETCODEISHIRING", numRows = 4
	输出: "LDREOEIIECIHNTSG"
	解释:
	
	L     D     R
	E   O E   I I
	E C   I H   N
	T     S     G

This problem is simpler if you think about it right, but if you don't think it right, then it's pretty circumstantial. When we see this topic, we may first think of finding a pattern. However, finding a pattern is not a simple matter and may cause a lot of trouble.

This requires us to change our thinking, we need to peel this string layer by layer. If you peel it horizontally, it’s a mathematical method. Find the general formula. If you peel it vertically by column, things are much simpler. When we read by column, we can maintain a string for each row. Append string just after one line.

The way to determine which line of append string is in is also very simple. We set two boundaries. When it grows to or decreases to a certain boundary, the order of reading lines is reversed, continuously from top to bottom, and then from Read from bottom to top until all strings are taken.

According to the above description, we can get such code, and the writing is clearer, so there is no need to explain it.

   public String convert(String s, int numRows) {
    
    
        if(s==null||s.length()==0||numRows<=1||s.length()<numRows){
    
    
            return s;
        }
        StringBuilder[] sbs=new StringBuilder[numRows];
        for(int i=0;i<numRows;i++){
    
    
            sbs[i]=new StringBuilder();
        }
        int layer=0;
        boolean turn=false;
        for(int i=0;i<s.length();i++){
    
    
            if(!turn){
    
    
                sbs[layer++].append(s.charAt(i));
            }else{
    
    
                sbs[layer--].append(s.charAt(i));
            }
            if(layer==-1||layer==numRows){
    
    
                layer=layer==-1?1:layer-2;
                turn=!turn;
            }
        }
        StringBuilder result=new StringBuilder();
        for(StringBuilder sb:sbs){
    
    
            result.append(sb.toString());
        }
        return result.toString();
    }

Guess you like

Origin blog.csdn.net/qq_23594799/article/details/106152335