leetcode中的一道题目:
【我的解法:】
#include "stdafx.h" #include <iostream> #include <vector> using namespace std; class Solution { public: string convert(string s, int numRows) { char ** str = new char* [numRows]; int numCols = s.length()/numRows + 1; for(int i = 0; i < numRows; i++){ str[i] = new char[numCols]; } vector<int> vStrEachRowNum; for(int i = 0; i < numRows; i++){ vStrEachRowNum.push_back(0); } int id = 0; for(id = 0; id < s.length(); id++){ int nValue = id/(2*(numRows - 1)); int nRemainder = id%(2*(numRows - 1)); int tempColId,tempRowId; if(nRemainder < numRows - 1){ tempRowId = nRemainder; tempColId = vStrEachRowNum.at(tempRowId); str[tempRowId][tempColId] = s.at(id); vStrEachRowNum[tempRowId] = tempColId+1; }else{ tempRowId = 2*numRows - nRemainder - 2; tempColId = vStrEachRowNum.at(tempRowId); str[tempRowId][tempColId] = s.at(id); vStrEachRowNum[tempRowId] = tempColId+1; } } string newS; for(int i = 0; i < numRows; i++){ str[i][vStrEachRowNum[i]] = 0; newS.append(str[i]); } return newS; } }; int main(){ Solution solution; solution.convert("PAYPALISHIRING", 3); return 0; }
【别人家的小孩解法:】
时间: 2024-10-25 03:23:50