zoukankan      html  css  js  c++  java
  • 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"

    刚开始没读懂,纠结好久才知道"ZigZag"形式是这样

    (吐槽一下,这明明是"N"嘛!)

     处理字符串,感觉指针有天然优势;

     1 //将p指向的字符串,写入二维数组show中
     2 for(int i=0;i<len;++i){//len 字符串长度
     3         show[row][column] = *(p+i);
     4         ++row;
     5         if(column%(row-1) == 0){//如果能整除说明正在写的那段字符是存在“Z”的“边”上
     6             if(row == row){
     7                 row -= 2;
     8                 ++column;
     9             }
    10         }
    11         else{
    12             row -= 2;
    13             ++column;
    14         }
    15     }

    而leetcode上需要用c++ 写,而且字符串是string 类。

     1 //O(N²) QAQ
     2 class Solution {
     3 public:
     4     string convert(string s, int nRows) {
     5         if(nRows == 1)
     6             return s; //第一次提交的时候系统提示 INPUT: "A" 1 RUNTIME ERROR 加上就可以ac了
     7         int len =s.size()/2; //根据上行,至少为2行
     8         char show[nRows][len];
     9         for(int i=0;i<nRows;++i)
    10             for(int j=0;j<len;++j)
    11                 show[i][j] = ' ';//初始化一个二维数组便于我们存放 “zigzag”形式的字符
    12         string::iterator it = s.begin();
    13         int row=0,column=0;
    14         for(int i =0;i<len;++i){
    15             show[row][column] = *it++;
    16             ++row;
    17             if(column%(nRows-1) == 0){// 判断是否是“Z”的“边”
    18                 if(row == nRows){
    19                     row -= 2;// 这里-=2,line 16 row自增了一次
    20                     ++column;
    21                 }
    22             }
    23             else {
    24                 row -= 2;
    25                 ++column;
    26             }
    27         }
    28         string res;
    29         for(int i=0;i<nRows;++i)
    30             for(int j=0;j<len;++j){
    31                 if(show[i][j] != ' ')
    32                     res.push_back(show[i][j]);
    33             }//按规定的形式读出来放入 string res 中
    34         return res;
    35     }
    36 };
  • 相关阅读:
    iphone备忘录存储路径
    wp7常用Task,启动器与选择器
    sql ce 修改表数据
    MessageBox.Show()中的换行
    莫名异常
    wp7中设置toolkit的工具栏图标不能正常显示(DatePicker和TimePicker)
    json 解析
    wp7弹出提示框退出程序
    第一个ios程序
    TextBox只显示数字
  • 原文地址:https://www.cnblogs.com/ittinybird/p/4148758.html
Copyright © 2011-2022 走看看