美文网首页
6.ZigZag Conversion(ZigZag转换)

6.ZigZag Conversion(ZigZag转换)

作者: 安东可 | 来源:发表于2017-08-02 13:32 被阅读375次

字符串“PAYPALISHIRING”以给定行数的锯齿形图案写成:(您可能希望以固定字体显示此模式以获得更好的可读性)

P   A   H   N
A P L S I I G
Y   I   R

然后逐行阅读:“PAHNAPLSIIGYIR”
编写将采用字符串的代码,并将此转换指定为多行:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) 应该返回 "PAHNAPLSIIGYIR".


找规律:两列看做一个组,这样子就行了

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.length();
        int col = numRows * 2 - 2;
        int row;
        string temp;
        if (numRows == 1){
            return s;
        }
        if (len %numRows == 0)
            row = len / numRows;
        else
            row = len / numRows + 1;
        //计算
        for (int j = 0; j < numRows; ++j)
        {
            for (int i = 0; i < row; ++i)
            {
                if ((i*col + j) < len)
                {
                    cout << s[i* col + j];
                    temp += s[i* col + j];
                }
                if ((j != 0) && (j != col - j) && (i*col + col - j<len))
                {
                    cout << s[i*col + col - j];
                    temp += s[i*col + col - j];
                }
            }
        }
        return temp;
    }
};

int main(){
    string s;
    int row;
    Solution sol;
    cout << "输入字符串和行数:" << endl;
    while (cin >> s>>row){
        s=sol.convert(s,row);
        cout <<"string: "<<s<< endl;
        cout << "输入字符串和行数:" << endl;
    }
    return 0;
}

【推荐代码】

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1) return s;
        string rel="";
        int l=s.length();
        int add=2*numRows-2;
        for(int i=0;i<numRows;i++){
            for(int j=i;j<l;j+=add){
                rel+=s[j];
                int flag=j+2*(numRows-1-i);
                if(i!=0&&i!=numRows-1&&flag<l){
                    rel+=s[flag];
                }
            }
        }
        return rel;
    }
};

相关文章

网友评论

      本文标题:6.ZigZag Conversion(ZigZag转换)

      本文链接:https://www.haomeiwen.com/subject/fjsslxtx.html