LeetCode 之 ZigZag Conversion — C 实现
来源:互联网 发布:qq聊天软件 编辑:程序博客网 时间:2024/05/16 06:56
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 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"
.字符串 "PAYPALISHIRING"
按照给定的行写成如下 Z 字形:
P A H NA P L S I I GY I R
然后按行读取为 "PAHNAPLSIIGYIR"
完成如下带有字符串和给定行的转换函数。
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
应该返回 "PAHNAPLSIIGYIR"
.
分析:
如果字符串个数小于给定行数,则输出只有一列。否则,对每个 Z 字形分成一个单元,按行计算每个字符对应新字符串的位置,除了第一行和最后一行,每个单元每次每行都要计算两个字符位置,注意每行第二个字符存在性的判断。
char* convert(char* s, int numRows) { char *pret = NULL, *temp = NULL; int icharLen = 0; int ilen = 0, irow = 0, inum = 0; int icount = 0, iunit; if(NULL == s || numRows == 0) /*空字符串行数不合法*/ return NULL; icharLen = strlen(s); pret = (char *)malloc(icharLen + 1); if(1 == numRows || numRows >= icharLen) /*输出为一行或者输出行数大于等于字符个数*/ { temp = pret; while(*temp++ = *s++); return pret; } iunit = 2*numRows-2; /*平均每单元字符个数*/ for(; irow < numRows; ++irow) { for(inum = 0; inum*iunit + irow < icharLen; ++inum) { pret[icount++] = s[inum*iunit + irow]; if(irow != 0 && irow != iunit/2)/*不是首尾两行,每次需要计算两个字符位置*/ { if(inum*iunit + iunit - irow < icharLen)/*判断第二个字符是否存在*/ { pret[icount++] = s[inum*iunit + iunit - irow]; } } } } pret[icharLen] = '\0'; return pret;}
0 0
- LeetCode 之 ZigZag Conversion — C 实现
- LeetCode-6-ZigZag Conversion(C语言实现)
- 【leetcode c++】ZigZag Conversion
- [LeetCode]ZigZag Conversion(C++)
- leetcode之ZigZag Conversion
- LeetCode之ZigZag Conversion
- leetcode之ZigZag Conversion
- LeetCode之ZigZag Conversion
- 【Leetcode】之ZigZag Conversion
- leetcode之ZigZag Conversion
- leetcode之ZigZag Conversion
- LeetCode 之 ZigZag Conversion
- LeetCode之路——ZigZag Conversion
- leetcode—zigzag conversion
- [C++]LeetCode: 11 ZigZag Conversion
- LeetCode::Zigzag Conversion C语言
- [C++] LeetCode #6 ZigZag Conversion
- Leetcode c语言-ZigZag Conversion
- HLJU 1220: AC100天 (枚举)
- VS2013 调试时的 0xCCCCCCCC 读取字符串的字符时出错
- java4Android(6)函数的复写(override)/对象的转型(向上转型/向下转型)
- NYOJ 20吝啬的国度(vector容器+dfs||邻接表+dfs)
- 07库函数编写
- LeetCode 之 ZigZag Conversion — C 实现
- 这些年看过的电影
- 推荐15个 Node.js 开发工具
- 辛星浅析html中的name和id的区别
- 比较基础常用的java面试题(3)
- 详解android:scaleType属性
- JavaScript学习总结-技巧、实用函数、简洁方法、编程细节
- FragmentPagerAdapter与FragmentStatePagerAdapter区别
- 标准非STL容器 : bitset