zoukankan      html  css  js  c++  java
  • [leetcode]ZigZag Conversion

    水题。主要就是画画图,找找规律。稍微要注意的是:1. nRow为1的情况;2. 采用变量index方便边界判断

    public class Solution {
        public String convert(String s, int nRows) {
            StringBuilder sb = new StringBuilder();
            if (nRows == 1) return s;
            // nRows >= 2
            for (int i = 0; i * (2 * nRows - 2) < s.length(); i++)
            {
                sb.append(s.charAt(i * (2 * nRows - 2)));
            }
            
            for (int i = 1; i < nRows - 1; i++)
            {
            	for (int j = 0;; j++)
                {
            		int index = j * (2 * nRows - 2) - i;
            		if ( index > 0 && index < s.length())
            		{
            			sb.append(s.charAt(index));
            		}
            		index = j * (2 * nRows - 2) + i;
            		if ( index > 0 && index < s.length())
            		{
            			sb.append(s.charAt(index));
            		}
            		else
            		{
            			break;
            		}
                }
            }
            
            // last
            if (nRows != 0 && nRows != 1)
            {
    	        for (int i = 0; i * (2 * nRows - 2) + nRows - 1 < s.length(); i++)
    	        {
    	        	sb.append(s.charAt(i * (2 * nRows - 2) + nRows - 1));
    	        }
            }
            
            return sb.toString();
        }
    }
    

    第二刷,先找规律,写公式,然后写代码,要注意行数为1的情况:

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

      

  • 相关阅读:
    【STL】栈stack
    【简单思考】noip2010提高组 乌龟棋
    【水】noip2010提高组 机器翻译
    【dp概率与期望】pattern
    【快速幂+中等难度】Calculation 哈工大HITOJ2901
    hdu--4502--dp
    hdu--4432--好久没做题了.
    hdu--5019--开始参加bc了
    字符串排列后匹配
    输出n的全排列的字典序编号为k的全排列
  • 原文地址:https://www.cnblogs.com/lautsie/p/3197073.html
Copyright © 2011-2022 走看看