Implement zigzag conversion that will take a string and make this conversion given a number of rows
Example:
Input: str="PAYPALISHIRING", n=3 Output: PAHNAPLSIIGYIR
Approach
Java
public class ZigZagConversion {public static void main(String[] args) {String str = "PAYPALISHIRING";int numRows = 3;System.out.println(convert(str, numRows));}// function to convert the given// string into the zigzag fashionstatic String convert(String s, int numRows) {int n = s.length();if (numRows == 1)return s;int k = 0, up = 0, r = 0;String res = "";String ans[] = new String[n];while (k < n) {// move upif (up == 0) {while (k < n && r < numRows) {if (ans[r] == null) {ans[r] = "" + s.charAt(k++);} else {ans[r] += s.charAt(k++);}r++;}up = 1;r = numRows - 2;}// move downelse {while (k < n && r >= 0) {if (ans[r] == null) {ans[r] = "" + s.charAt(k++);} else {ans[r] += s.charAt(k++);}r--;}up = 0;r = 1;}}for (int i = 0; i < n; i++) {if (ans[i] != null) {res += ans[i];}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;//function to convert the given//string into the zigzag fashionstring convert(string s, int numRows){int n=s.size();if(numRows==1)return s;int k=0,up=0,r=0;string res="",ans[n];while(k<n){//move upif(up==0){while(k<n&&r<numRows){ans[r++]+=s[k++];}up=1;r=numRows-2;}//move downelse{while(k<n && r>=0){ans[r--]+=s[k++];}up=0;r=1;}}for(int i=0;i<n;i++)res+=ans[i];return res;}int main(){string str = "PAYPALISHIRING";int numRows = 3;cout<<convert(str,numRows);return 0;}
No comments:
Post a Comment