6. 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”.

题目描述:

给出一个整数数组和一个整数target,找出数组中两数之和等于target的数的索引

Solution:

维护两个指针指向当前相加的数组元素位置索引,依次向后移动,直到和等于target,把结果索引保存在一个长度为2的数组中,返回

java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

public class {
public String convert(String s, int numRows) {
StringBuilder result=new StringBuilder();
if(s==null||numRows==0){
return result;
}
if(numRows==1){
return s;
}
for(int i=0;i<numRows;i++){
int n=2*numRows-2;
for(int j=i;j<s.length();j+=n){
result.append(s.charAt(j);
if(i!=0&&i!=(numRows-1)){
int temp=j+n-2*i;
if(temp<s.length())
result=result+s.charAt(temp);
}
}
}
return result;
}
}