6.ZigZag Conversion

来源:互联网 发布:c语言漫画 编辑:程序博客网 时间:2024/06/06 00:45

6.ZigZag Conversion

  • 题目描述:The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

    P   A   H   NA P L S I I GY   I   R

    And then read line by line:

    "PAHNAPLSIIGYIR"

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

    string convert(string text, int nRows);

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

  • 题目大意:进行字符串转化

  • 代码

    package String;import org.omg.CORBA.INTERNAL;/*** @Author OovEver* @Date 2017/12/10 21:16*/public class LeetCode6 {  public static String convert(String s, int numRows) {      char[] c = s.toCharArray();      StringBuilder []stringBuilder = new StringBuilder[numRows];      for(int i=0;i<stringBuilder.length;i++) {          stringBuilder[i] = new StringBuilder();      }      int len = c.length;      int i = 0;      while (i < len) {          for(int idx=0;idx<numRows&&i<len;idx++) {//                处理每列              stringBuilder[idx].append(c[i++]);          }          for(int idx=numRows-2;idx>=1&&i<len;idx--) {//                处理对角线              stringBuilder[idx].append(c[i++]);          }      }      for(int j=1;j<numRows;j++) {          stringBuilder[0].append(stringBuilder[j]);      }      return stringBuilder[0].toString();  }  public static void main(String[] args) {  }}