[leetcode]ZigZag Conversion

題目: https://oj.leetcode.com/problems/zigzag-conversion/ https://oj.leetcode.com/problems/zigzag-conversion/


需要找到每行各種字符對應在源字符的位置,即找出兩者之間的規律。這題就比較好解了。


代碼:

class Solution {
public:
    string convert(string s, int nRows) {
        if (s.length() == 0 || nRows <= 0) return "";
		if (nRows == 1) return s;
		string res = s;
		int nums = 2 * nRows - 2;
		int index = 0;
		for (int i = 0; i<nRows; i++)
		{
			for (int j = i; j<s.length(); j += nums)
			{
				res[index++] = s[j];
				if (i != 0 && i != nRows-1 && j + nums - 2 * i<s.length())
				{
					res[index++] = s[j + nums - 2 * i];
				}
			}
		}
		return res;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章