zoukankan      html  css  js  c++  java
  • 【java】6. ZigZag Conversion

      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   N
    A P L S I I G
    Y   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".

     n=4时的走法是:

     0       6         12

     1   5  7    11 13

     2 4    8 10    14

     3       9         15 

    解法:

    对于第一行与最后一行,间隔均为2*n-2.

    对于中间的斜行,间隔为当前列j+(2n-2)-2i(i是行).

    java实现:

     1 public String convert(String s, int nRows) {  
     2         if(s == null || s.length()==0 || nRows <=0)  
     3             return "";  
     4         if(nRows == 1)  
     5             return s;
     6             
     7         StringBuilder res = new StringBuilder();  
     8         int size = 2*nRows-2;  
     9         for(int i=0;i<nRows;i++){  
    10             for(int j=i;j<s.length();j+=size){  
    11                 res.append(s.charAt(j));  
    12                 if(i != 0 && i != nRows - 1){//except the first row and the last row
    13                     int temp = j+size-2*i;
    14                     if(temp<s.length())
    15                         res.append(s.charAt(temp));
    16                 }
    17             }                  
    18         }  
    19         return res.toString();  
    20     }
  • 相关阅读:
    正则表达式基础以及应用
    日常使用之css篇
    echarts的使用总结
    &#65279导致页面顶部空白一行
    vue.js单页面应用实例
    BFC的外边距折叠
    .net 跳出Frameset框架
    Cache缓存使用
    Kafka集群搭建及安全机制手册
    PHP学习笔记
  • 原文地址:https://www.cnblogs.com/carsonwuu/p/8012465.html
Copyright © 2011-2022 走看看