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

解题:

引用http://blog.csdn.net/zhouworld16/article/details/14121477的图片说明:

所谓的ZigZag,就是这样的:

因此可以找到每行排列数字的规律,nRows = n,字符串字符下标从0开始。

普通青年:

①   先读第1行:0, 0 + 2n-2, 0 + (2n-2)*2,...

②   读第2行至第n-2行,设行数为e,则每行读取数字为:

  e-1,e-1 + 2n-2 - (e-1)*2, e-1 + 2n-2, e-1+2n-2 + 2n-2 - (e-1)*2, ...

  规律即,两个数字一组,每组间隔2n-2:

  for (int i=e-1; i<string.length(); i+=2n-2) {

    每组元素可表示为i 和 i + 2n-2 - (e-1)*2

  }

③  读最后一行:n-1, n-1 + 2n-2, n-1 + (2n-2)*2, ...

(由于每循环一组,会读出两个数字。注意判定字符串越界)

 class Solution {
public:
string convert(string s, int nRows) {
string res;
int len = s.length(); if (nRows == )
return res; if (nRows == )
return s; for(int i=; i<len; i+=*nRows-)
res.push_back(s[i]); int index = ;
while(nRows--index){
for(int i=index; i<len; i+=*nRows-) {
res.push_back(s[i]);
int zig = i + 2 * nRows - 2 * index - ;
if (zig < len)
res.push_back(s[zig]);
}
index++;
} for(int i=nRows-; i<len; i+=*nRows-)
res.push_back(s[i]); return res; }
};

聪明的青年:

类似于期末考试考场排座位,一般为蛇形排号。将考场的座位按一竖列为一组,编号时,第一组的座位从前向后编号,对第二组从后向前进行编号,如下图:

① ⑧ ⑨

② ⑦       ...

③ ⑥

④ ⑤

nRows即为每组能坐多少人。因此先让同学们按编号入座,再从前向后按横排依次读出他们的编号即为本题答案。

 class Solution {
public:
string convert(string s, int nRows) {
string sArray[nRows];
string res = "";
int index = ; if (nRows == )
return s; for(int i=; i<s.length(); ++i){
sArray[index] += s[i]; if (!(i / (nRows-) % )) {
index++;
} else {
index--;
}
} for(int i=; i<nRows; ++i){
res += sArray[i];
} return res;
}
};

当然是原创的。

【Leetcode】【Easy】ZigZag Conversion的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  3. 【LeetCode题意分析&解答】35. Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  4. ACM金牌选手整理的【LeetCode刷题顺序】

    算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...

  5. 【LeetCode算法题库】Day2:Median of Two Sorted Arrays & Longest Palindromic Substring & ZigZag Conversion

    [Q4] There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of th ...

  6. 【leetcode刷题笔记】ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  7. 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number

    [Q7]  把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...

  8. 【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists

    [Q19] Given a linked list, remove the n-th node from the end of list and return its head. Example: G ...

  9. 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman

    [Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...

  10. 【LeetCode算法题库】Day1:TwoSums & Add Two Numbers & Longest Substring Without Repeating Characters

    [Q1] Given an array of integers, return indices of the two numbers such that they add up to a specif ...

随机推荐

  1. UVA - 11996 可持久化Treap 维护Hash Ver.2

    这回总算是过了.. 4600ms+,服务器抖一抖又没了 对于极端卡时间的情况还是考虑屈服于Splay吧 #include<iostream> #include<algorithm&g ...

  2. php 的基本语法

    八种数据类型: 4种标量类型:boolean.integer.float.string 2种复合类型:array.object 2种特殊类型:resource.NULL 如果想看某个表达式的值和类型用 ...

  3. linux 文件截取

    相关函数:open, ftruncate 表头文件:#include <unistd.h> 定义函数:int truncate(const char *path, off_t length ...

  4. base64的python实现

    写了一个函数,自己按照base64的规则转换一个字符串. # /usr/bin/python # encoding: utf-8 base64_table = ['A', 'B', 'C', 'D', ...

  5. Merge Sorted Array II

    Merge two given sorted integer array A and B into a new sorted integer array. Example A=[1,2,3,4] B= ...

  6. 转 LIST INCARNATION OF DATABASE

    incarnation在英文中是“化身”的意思. 那么在oracle中,它又是什么意思呢?有什么作用呢? 我们看一些基本概念 Current Incarnation(当前化身):数据库当前正在使用的化 ...

  7. 文献综述八:基于JAVA的商品网站的研究

    一.基本信息 标题:基于JAVA的商品网站的研究 时间:2015 出版源:信息技术 文件分类:对java语言的研究 二.研究背景 本文主要介绍了系统的分析,设计和开发的全部过程. 三.具体内容 文献的 ...

  8. Python+Selenium之通过batch跑脚本

    例如在执行路径C:\Portal_Scripts\Scripts下的脚本CreateIndicativeBOP.py,可以在notepad里面编写如下: @echo off cd  C:\Portal ...

  9. pyspark 读写csv、json文件

    from pyspark import SparkContext,SparkConf import os from pyspark.sql.session import SparkSession de ...

  10. Coursera 机器学习 第8章(上) Unsupervised Learning 学习笔记

    8 Unsupervised Learning8.1 Clustering8.1.1 Unsupervised Learning: Introduction集群(聚类)的概念.什么是无监督学习:对于无 ...