美文网首页
leetcode6 关于C++ string

leetcode6 关于C++ string

作者: 追风少年王二狗 | 来源:发表于2018-12-26 00:34 被阅读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读取某个元素

  • at函数可以直接返回某个位置的值
    returnstr[pos++]=s.at(oldpos);
  • []可以直接进行取值
    returnstr[pos++]=s[oldpos];

string添加某个元素

  • append添加的类型有限制
  • 还是直接使用[]添加比较好

leetcode操作

主体思想

  • 使用map,将新旧数组的位置关联起来
  • 由于是齿形结构所以大家都有规律

遇到的小问题

  • 数组越界
    Error in 'sandbox run': free(): invalid next size (normal): 0x0000000001880ce0
  • 可能除以0的情况
    Line 9: Char 26: runtime error: division by zero (solution.cpp)
  • 对于第一行和最后一行的处理

代码

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>两个头文件今天居然是编译第一个难关。

相关文章

网友评论

      本文标题:leetcode6 关于C++ string

      本文链接:https://www.haomeiwen.com/subject/ihkclqtx.html