1. 程式人生 > >LeetCode-06 Z字形變換

LeetCode-06 Z字形變換

C++版本

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

C++版本簡單易理解,我又寫了C版本。

C版本

char* convert(char* s, int numRows) {  
    if(numRows<=1) return s;
    char *s1 = (char *)malloc(sizeof(char) * (strlen(s) + 1));
    int k = 0;
    int length_cycle = 2*numRows - 2;
    for(int i = 0; i < numRows; i++)
        for(int j = i; j < strlen(s); j += length_cycle)
        {
            // strcat(s1,s+j);
            //s1 += s[j];
            s1[k++] = s[j];
            int temp = j + length_cycle -2 * i;
            if(i != 0 && i != numRows -1 && temp < strlen(s)) 
               //strcat(s1,s+temp); 
                //s1 += s[temp];
            s1[k++] = s[temp];
        }
   s1[k]=0;
   return s1;
}

最後那個s1[k]=0必須要寫啊,要不然測試不通過。C和C++有些語法不通用,有時候容易搞混。