6 ZigZig変換[M] Z字型変換

タイトル

Z字状の配置から左から右へ、下へ、文字列、行の指定された数を与え。
例えば:

Input: s= "ABCDEFGHIJKLMNOP",  numRows = 4,
Output:AGMBFHLNCEIKODJP
Explanation:
           A    G    M
           B  F H  L N
           C E  I K  O
           D    J    P

アイデア:

第1ストリング\(S \) Z-ワードが整列し、文字列を読み取ります。Z分割下部に三つに、Zの例:ABCD、で:EF、下部:GHIJ。法律行の指定された数のために見つけることができる分析\(N- \) 中間の数である(\ 2-N-)\、上部+の各サイクルとして、サイクル\(T = N + 2-N- \) そこ
行1:\(S [0]、S [T + 0]、S [0 CDOT T \ + 2]、\ cdots; \)
2行目:\(Sの[1]、S [0+ 。。T-1]、Sの[1 + T]、\ cdots; \)
\(\ cdots \)
\(\)N-ライン:\(S [N - 1]、S [N - 1 + T]、S。 [N-1 + 2 \ CDOTの T] \ cdots。\)

コード:

  • C ++
class solution{
public:
  string convert(string s, int numRows){
    if(s.size()==1) return s;
    string resString;
    int stringLen=s.size();
    int cycleLen=2*numRows-2;

    for(int i=0;i<numRows;i++){
      for(int j=0;j+i<stringLen;j+=cycleLen){
        resString += s[i+j];
        if(i !=0 && i != numRows-1 && j+cycleLen-i < stringLen){
         resString+=s[j + cycleLen - i];
      }
    }
    return resString;
  }
};
  • パイソン
def covert

おすすめ

転載: www.cnblogs.com/Jessey-Ge/p/10993428.html