难度:中等
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
Java实现:
public class topic6 {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
String result = convert(s,3);
System.out.println(result);
}
public static String convert(String s, int numRows) {
StringBuffer str = new StringBuffer();
int length = s.length();
int dis = (numRows-1)*2;
if(length<=0||dis==0) {
return s;
}
for(int i=0;i<numRows;i++) {
for(int j=0;j+i<length;j+=dis) {
str.append(s.charAt(j+i));
if(i!=0&&i!=numRows-1&&j+dis-i<length) {
str.append(s.charAt(j+dis-i));
}
}
}
return str.toString();
}
}
C语言实现:
char* convert(char* s, int numRows);
int main(int argc, const char * argv[]) {
@autoreleasepool {
char* s = "agqapkdophrispmkptlattjelegorxbufruwdymshdbzvplkiykbuwgfcowtlznsrkpwib";
char* result = convert(s, 18);
printf("%s\n",result);
}
printf("\n");
return 0;
}
char* convert(char* s, int numRows) {
long length = strlen(s);
char* str = (char*)malloc(sizeof(char)*length);
int num=0;
int dis = (numRows-1)*2;
if (length<=1||dis==0) {
return s;
}
for (int i=0; i<numRows; i++) {
for (int j=0; j+i<length; j+=dis) {
printf("%d %c\n",i+j,s[i+j]);
str[num] = s[i+j];
num++;
if (i!=0&&i!=numRows-1&&j+dis-i<length) {
str[num] = s[j+dis-i];
num++;
}
}
}
str[num] = '\0';
return str;
}
网友评论