输出之字形结构

 
  
void printZigzag(const string &s, int nRows)  
{  
    if(s.empty() || nRows < 1) return;  
    if (nRows == 1)  
    {  
        cout<<s<<endl;  
        return;  
    }  
   
    int zigSpan = nRows*2 - 2;  
    int zig = nRows - 2;  
    for (int i = 0; i < nRows; i++)  
    {  
        for (int j = i; j < s.length(); j+=zigSpan)  
        {  
            cout<<s[j];  
            //注意:推导出zigSpan+j-2i的数学公式,一点都不能错  
            if (i != 0 && i != nRows-1 && zigSpan+j-2*i<s.length())  
            {  
                for (int r1 = 0; r1 < zig-i; r1++)  
                {  
                    cout<<" ";  
                }  
                cout<<s[zigSpan+j-2*i];  
                for (int r2= 0; r2 < i-1; r2++)  
                {  
                    cout<<" ";  
                }  
            }  
            else 
            {  
                for (int r = 0; r < zig; r++)  
                {  
                    cout<<" ";  
                }  
            }  
        }  
        cout<<endl;  
    }  
}  
   
   
int main()  
{  
    string str1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";  
    Solution solu;  
    int nRows = 5;  
    //string str2 = solu.convert(str1, nRows);  
    //cout<<str2<<endl;  
   
    printZigzag(str1, nRows);  
   
    system("pause");  
    return 0;  
}  
5行的时候

你可能感兴趣的:(输出之字形结构)