Created
July 9, 2013 08:53
-
-
Save luoxiaoxun/5955785 to your computer and use it in GitHub Desktop.
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 conver…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
C++: | |
class Solution { | |
public: | |
string convert(string s, int nRows) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(nRows==1) return s; | |
string temp[nRows]; | |
int idx=-1; | |
int step=1; | |
for(int i=0;i<s.size();i++){ | |
idx +=step; | |
if(idx==nRows){ | |
idx=nRows-2; | |
step=-1; | |
} | |
else if(idx==-1){ | |
idx=1; | |
step=1; | |
} | |
temp[idx] +=s[i]; | |
} | |
string ret; | |
for(int i=0;i<nRows;i++) ret+=temp[i]; | |
return ret; | |
} | |
}; | |
Java: | |
public class Solution { | |
public String convert(String s, int nRows) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(nRows==1) return s; | |
StringBuilder[] temp=new StringBuilder[nRows]; | |
for(int i=0;i<temp.length;i++) temp[i]=new StringBuilder(); | |
int idx=-1; | |
int step=1; | |
for(int i=0;i<s.length();i++){ | |
idx +=step; | |
if(idx==nRows){ | |
idx=nRows-2; | |
step=-1; | |
}else if(idx==-1){ | |
idx=1; | |
step=1; | |
} | |
temp[idx].append(s.charAt(i)); | |
} | |
String ret=""; | |
for(int i=0;i<nRows;i++) ret+=temp[i].toString(); | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment