C++中string的輸入
使用scanf輸入(未自己驗(yàn)證)
- 首先聲明string糜值;
- 分配空間旭斥;
- 輸入首地址;
string a;
a.resize(100); //需要預(yù)先分配空間
scanf("%s", &a[0]);
使用cin輸入
直接使用cin進(jìn)行輸入
string input; cin>>input;
C++中string的操作
string讀取某個(gè)元素
- at函數(shù)可以直接返回某個(gè)位置的值
returnstr[pos++]=s.at(oldpos);
- []可以直接進(jìn)行取值
returnstr[pos++]=s[oldpos];
string添加某個(gè)元素
- append添加的類(lèi)型有限制
- 還是直接使用[]添加比較好
leetcode操作
主體思想
- 使用map,將新舊數(shù)組的位置關(guān)聯(lián)起來(lái)
- 由于是齒形結(jié)構(gòu)所以大家都有規(guī)律
遇到的小問(wèn)題
- 數(shù)組越界
Error in 'sandbox run': free(): invalid next size (normal): 0x0000000001880ce0
- 可能除以0的情況
Line 9: Char 26: runtime error: division by zero (solution.cpp)
- 對(duì)于第一行和最后一行的處理
代碼
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>
兩個(gè)頭文件今天居然是編譯第一個(gè)難關(guān)藐石。