Interview Question
Country: United States
Write PAYPALISHIRING in the zig-zag shape (|/|/|/|)
P A H N
A P L S I I G
Y I R
Thanks,
Laxmi
import java.lang.Math;
class StringManip
{
public static void main(String args[])
{
String str = "PAY PAL IS HIRING ME";
int len = str.length();
int rows = 3;
double cols;
cols = (double)len/rows;
//System.out.println(cols);
int columns = (int)Math.ceil(cols);
str=str.replaceAll(" ","");
System.out.println("Input: "+str);
System.out.println("Length: "+len);
System.out.println("Cols: "+columns);
System.out.println("Rows: "+rows);
len = str.length();
char[][] a = new char[rows][columns];
int pos=0;
for(int i=0;i<columns;i++)
{
for(int j=0;j<rows;j++)
{
if(pos<len)
{
a[j][i]=str.charAt(pos);
pos++;
}
else
{
a[j][i]=' ';
}
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
package com.learn;
public class ZIGZAGPattern
{
public static void main(String[] args)
{
ZIGZAGPattern pattern = new ZIGZAGPattern();
pattern.strConvertToZigZag("PAYPALISHIRING",3);
}
public void strConvertToZigZag(String str, int rows)
{
StringBuffer []sb = new StringBuffer[rows];
for(int i=0;i<rows;i++)
{
sb[i] = new StringBuffer();
}
int count=0;
int len = str.length();
while(count < len)
{
char c;
for(int j=0; j<rows && count<len; j++)
{
c = str.charAt(count);
sb[j].append(c);
count++;
}
for(int j=rows-2; j>0 && count<len; j--)
{
c = str.charAt(count);
sb[j].append(c);
count++;
}
}
for(int j=0; j <rows ;j++)
{
System.out.println(sb[j].toString());
}
}
}
Enter the message
This is not my story
Enter the number of line
5
T i t s
h s t
i m o
s n y r
o y
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int leng(char *a)
{
int temp;
while(*a++) temp++;
return temp;
}
int main()
{
char arr[256],ar[8][16]={"XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX","XXXXXXXXXXXXXXXX"};
int i=0,j=0,k=0,p=0,line,len;
printf("Enter the message\n");
gets(arr);
len=leng(arr);
printf("Enter the number of line\n");
scanf("%d",&line);
while(arr[k])
{
for(j=0;j<line;j++)
ar[j][i]=arr[k+j];
i++;
k=k+line;
}
k=0;
for(i=0;i<line;i++)
{
printf("\n");
for(j=0;j<16;j++)
{
if(len!=k++&& (char)ar[i][j]=='X')
printf("%c%c",' ',' ');
else if(len!=k)
printf("%c%c",(char)ar[i][j],' ');
}
}
}
its just the function, doesn't check for the invalid input,
public static string convert(string text, int nRows)
{
string tmp = "";
nRows++;
int nrows = nRows;
for (int i = 0; i < nRows - 1 ; i++)
{
if (i % 2 == 1)
nRows /= 2;
tmp += text[i].ToString();
for (int j = i + nRows; j < text.Length; j += nRows)
tmp += text[j].ToString();
nRows = nrows;
}
return tmp;
}
Hi,
- N.A. December 06, 2011I didnt understand what the interviewer is trying to ask?? can somebody explain me the problem?? Is this a generic problem or specific to the string mentioned "PAYPAL IS HIRING"