1 classSolution {2 Public:3 stringConvertstringSintnRows) {4 stringA="";5 intlen=s.length ();6 if(len<=nrows| | nrows==1)returnS//only n, less than one cycle | | Row by line7 intteams=len/(nrows*2-2);//teams a complete cycle8 intrest=len% (nrows*2-2);//number of elements in the last insufficient complete period9 intk=0, i=0, j=0;Ten for(i=0; i<nrows;i++){ Onek=i; A for(j=0; j<teams;j++){ -a+=S[k]; - if(i!=0&& i!=nrows-1){//there are two in each cycle thea+=s[(nrows*2-2) * (j+1)-i]; - } -k+=nrows*2-2; - } + if(i<rest) -a+=S[k]; + if(Rest>nrows && rest> (nrows*2-2-i) && (nrows*2-2-I.) >=nRows) Aa+=s[(nrows*2-2) * (j+1)-i]; at } - returnA; - } -};ZigZag Conversion
Test instructions: Arranges a string of letters in the Z-word (similar to the Leetcode topic), and then returns them together as rows.
Ideas: by cycle, each n-2 for a cycle, the last may be less than a cycle, to special treatment. Because the z-word in a cycle is folded, it takes two of them to add up in a cycle.
Spit Groove: This method is not streamlined, but the operating time is 96ms. The internet is a bit of someone else's streamlined code, it is really beautiful, but the time reached 168ms. I'd better use this for the time being. Data analysis said some incredibly 50 a few MS will be done, code OH ~
Leetcode ZigZag Conversion (string into Z-font)