LeetCode::Zigzag Conversion C语言
来源:互联网 发布:js 滑动特效 编辑:程序博客网 时间:2024/05/15 23:24
题目
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 RAnd 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"
.分析
其实只有一个难点,只有发现了规律就很简单了。第一行和最后一行都是没有斜边的,间隔是(2*nRows - 2)其中nRows是总行数;
有斜边的中间几行其实也有规律,斜边上的数字到左边那个列的距离是(2*nRows - 2 - 2*row)其中row是当前行的行号。
明白这两个规律就行了。
C语言代码 注意就算s只有一行,也不能return s; 要malloc 内存 strcpy 再返回。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *convert(char *s, int nRows)
{
if ((NULL == s) | (nRows < 1))
{
return NULL;
}
// + 1 for NIL or '\0' in the end of a string
const size_t len = strlen(s);
char* output = (char*) malloc(sizeof(char) * ( len + 1));
char* head = output;
output[len] = '\0';
if ( 1 == nRows )
{
return strcpy(output, s);
}
for (int row = 0; row < nRows; ++row)
{
//processing row by row using (2nRows-2) rule
for (unsigned int index = row; index < len; index += 2*nRows-2)
{
// if it is the first row or the last row, then this is all
*output++ = s[index];
// otherwise, there are middle values, using (2nRows-2-2*row) rule
// notice that nRows-1 is the last row
if ( (row>0)&(row<nRows-1) & ((index+2*nRows - 2 - 2*row) < len))
{
*output++ = s[index+2*nRows - 2 - 2*row];
}
}
}
return head;
}
int main()
{
char* input = (char*)"A";
int rows = 1;
char* output = convert(input, rows);
if (NULL != output)
{
printf("input: %s; output: %s\n", input, output);
free(output);
}else
{
printf("empty\n");
}
}
0 0
- LeetCode::Zigzag Conversion C语言
- Leetcode c语言-ZigZag Conversion
- LeetCode-6-ZigZag Conversion(C语言实现)
- 【leetcode c++】ZigZag Conversion
- [LeetCode]ZigZag Conversion(C++)
- [C++]LeetCode: 11 ZigZag Conversion
- [C++] LeetCode #6 ZigZag Conversion
- LeetCode 之 ZigZag Conversion — C 实现
- 【LeetCode算法练习(C++)】 ZigZag Conversion
- [C++]LeetCode 6: ZigZag Conversion(ZigZag排序)
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- 【leetcode】Zigzag Conversion
- [LeetCode]ZigZag Conversion
- B+树与B*树小结
- Project2.c
- 验证数字的正则表达式集
- FreeRTOS STM32移植笔记
- C++ 虚函数virtual
- LeetCode::Zigzag Conversion C语言
- 汇编 INT 21H 指令
- 数据存取
- 第5章7节《MonkeyRunner源码剖析》Monkey原理分析-启动运行: 循环获取并执行事件 - runMonkeyCycles(原创)
- 【设计模式】装饰者模式
- BestCoder Round #32
- GameBuilder开发游戏应用系列之100行代码实现贪吃蛇
- 《数据结构编程实验》 2.4.2The 3n + 1 problem
- Android slidingmenu详解 优化侧滑