java - Zigzag conversion -


question : string "paypalishiring" written in zigzag pattern on given number of rows this: (you may want display pattern in fixed font better legibility)

p     h   n p l s i g y     r 

and read line line: "pahnaplsiigyir"

i have written below code, appearantly works fine, might miss corner cases. me find corner cases question on answer?

public static string zigzagconversion(string s , int rownum){      if (s == null){         throw new illegalargumentexception();     }     if (rownum == 1){         return s;     }     stringbuilder str = new stringbuilder();      int step = 2 * rownum - 2 ;      (int = 0 ; < rownum ; i++){          if( == 0 || == rownum -1){              (int j = ; j < s.length() ; j +=step){                  str.append(s.charat(j));                                 }                        }          else{              int step2 = 2* (rownum - - 1);             int step3 = step - step2;             int k = i;             boolean flag = true;              while (k < s.length()){                 str.append(s.charat(k));                  if(flag){                                            k += step2;                     flag = false;                 }                 else{                                            k +=step3;                    flag = false;                 }              }                         }     } return str.tostring();       } 

it gives incorrect output "paypalishiring", 4

p        n   l s  g y   h r p     

so correct answer should pinalsigyahrpi.

but program gives pinaligyaihrnpi: "s" missing, 1 "i" , 1 "n".

your revised version still incorrect, gives pinalsiigyahnpi.

the problem in while loop in middle. need alternate step counting, setting flag on , off. mistake set off once, , never on again.

str.append(s.charat(k)); if (flag) {     k += step2;     flag = false; } else {     k += step3;     flag = true; } 

with correction, believe solution correct. (i added minor improvement there, extracting common str.append(s.charat(k)); if-else branches.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -