leetcode6 关于C++ string

2018-12-26  本文已影响0人  追风少年王二狗

C++中string的输入

使用scanf输入(未自己验证)

  1. 首先声明string;
  2. 分配空间;
  3. 输入首地址;
string a;
a.resize(100); //需要预先分配空间
scanf("%s", &a[0]);

使用cin输入

直接使用cin进行输入
string input; cin>>input;

C++中string的操作

string读取某个元素

string添加某个元素

leetcode操作

主体思想

遇到的小问题

代码

class Solution {
public:
    string convert(string s, int numRows) {
        // the map from the new to the old
        string returnstr;
        returnstr.clear();
        returnstr.resize(100);
        int oneround,rounds,pos=0;//the number of chars in one round and the other is rounds
        oneround=2*numRows-2;
        // when the number is 0
        if(oneround==0){
            return s;
        }
        rounds=s.length()/oneround;
        // the special situation
        if(s.length()%oneround==0)
            rounds--;
        for(int row=0;row<numRows;row++){
            for(int round=0;round<=rounds;round++){
                int oldpos=round*oneround;
                if(row==0){
 //                   returnstr[pos++]=s[oldpos];
                      returnstr[pos++]=s.at(oldpos);
 //                   returnstr.append((const char)s.at(oldpos));
                    continue;
                }
                oldpos+=row;
                if(oldpos>=s.length()){
                    continue;
                }
                returnstr[pos++]=s[oldpos];
 //               returnstr.append(1,s.at(oldpos));
                oldpos+=oneround-2*row;
                if(oldpos<s.length()&&row!=numRows-1){
                        returnstr[pos++]=s[oldpos];
 //                   returnstr.append(1,s.at(oldpos));
                }
            }
        }
        return returnstr;
    }
};

PS: using namespace std;#include <iostream>两个头文件今天居然是编译第一个难关。

上一篇 下一篇

猜你喜欢

热点阅读