leetcode-6 ZigZag Conversion Z形字符串输出



问题描述:

The string"PAYPALISHIRING" is written in a zigzag pattern on agiven number of rows like this: (you may want to display this pattern in afixed font for better legibility)

P  A  H   N

A P L S I I G

Y  I   R

And then read line by line:"PAHNAPLSIIGYIR"

Write the codethat will take a string and make this conversion given a number of rows:

stringconvert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".



解法一:公式法


/*
   0       8        16
   1     7 9      15
   2   6   10   14  
   3 5     11 13
   4       12

*/


public class Solution {
    public String convert(String s, int nRows) {
		
		//参数判断
		if(s == null || s.length() == 0 || nRows <= 1)
		{
			return s;
		}
		
		char[] strarr = s.toCharArray();
		StringBuilder strBuilder = new StringBuilder();
		boolean flag = true;
		int temp_index = 0;

		for(int i = 0 ; i < nRows; i++)
		{
			flag = true;
			for(int j = 0; flag ; j++)
			{
				flag = false;
				if( i == 0 || i == nRows - 1)//第一行和最后一行情况
				{
					temp_index = 2 * j * (nRows - 1) + i;
				}
				else 
				{
					if((j & 0x1) == 0)//偶数情况
					{
						temp_index = i + j * (nRows - 1);
					}
					else
					{
						temp_index = i + 2 * (nRows - 1 - i) + (j / 2 * 2) * (nRows - 1);
					}
				}
				
				if(temp_index < s.length())
				{
					strBuilder.append(strarr[temp_index]);
					flag = true;
				}		
			}
		}
        return strBuilder.toString();
    }
}



解法二:列举所有可能


public class Solution {
    public String convert(String s, int nRows) {
		
		//参数判断
		if(s == null || s.length() == 0 || nRows <= 1)
		{
			return s;
		}
		
		char[] strarr = s.toCharArray();
		StringBuilder strBuilder = new StringBuilder();
		boolean flag = true;
		int temp_index = 0;

		for(int i = 0 ; i < nRows; i++)
		{
			flag = true;
			for(int j = 0; flag ; j++)
			{
				flag = false;
				if( i == 0 || i == nRows - 1)//第一行和最后一行情况
				{
					temp_index = 2 * j * (nRows - 1) + i;
					if(temp_index < s.length())
					{
						strBuilder.append(strarr[temp_index]);
						flag = true;
					}	
				}
				else 
				{
					temp_index = 2 * j * (nRows - 1) - i;
					if ((temp_index > 0)&&(temp_index < s.length()))
					{
						strBuilder.append(strarr[temp_index]);
						flag = true;
					}
						
					temp_index = 2 * j * (nRows - 1) + i;
					if(temp_index < s.length())
					{
						strBuilder.append(strarr[temp_index]);
						flag = true;
					}
				}
			}
		}
        return strBuilder.toString();
    }
}


你可能感兴趣的:(leetcode-6 ZigZag Conversion Z形字符串输出)