• LeetCode 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".

    0       8       16      
    1     7 9     15 17      
    2   6   10   14   18      
    3 5     11 13     19      
    4       12       20      

    分两次循环,第一次是列,第二次是斜线。

    java需使用stringbuffer才不会超时,使用string超时了。

     1 public class Solution {
     2     public String convert(String s, int nRows) {
     3         if (nRows==1) {
     4             return s;
     5         }
     6        
     7         StringBuffer[]    reBuffers=new StringBuffer[nRows];
     8         for (int i = 0; i < reBuffers.length; i++) {
     9             reBuffers[i]=new StringBuffer();
    10         }
    11         int i=0,j=0,C=nRows-2;
    12         while (i<s.length()) {
    13             for (j = 0; j<nRows&&i<s.length() ;j++) {
    14         
    15                 reBuffers[j].append(s.charAt(i++));
    16                 
    17             }
    18             
    19             for (j = C; i<s.length()&&j>0;j--) {
    20                 
    21                 reBuffers[j].append(s.charAt(i++));
    22                 
    23             }
    24             
    25         }
    26         
    27         StringBuffer    res=new StringBuffer();
    28         for (int k = 0; k < nRows; k++) {
    29             res.append(reBuffers[k]);
    30         }
    31         return res.toString();
    32     }
    33 }
  • 相关阅读:
    AutoMapper用法
    这些基础却重要的面向对象概念,你还记得多少
    Ajax工作原理
    CSS中的绝对定位与相对定位
    NET中的Memcached.ClientLibrary使用详解
    经典Linq实例语句
    软件工程的意义
    C#.Net Mvc运营监控,计算方法/接口/action/页面执行时间
    属性与字段的区别
    SQL 递归树 子父节点相互查询
  • 原文地址:https://www.cnblogs.com/birdhack/p/4066174.html
Copyright © 2020-2023  润新知