题意:
输入一个字符串和一个整数 k ,截取字符串的前k个字符并输出。
方法一:
C++函数
思路:调用C++函数 substr(start,len)
其中start为起始下标,len为长度。
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
int x;
while(cin >> s >> x){//输入
cout << s.substr(0,x) << endl;//截取前x个字符并输出
}
return 0;
}
时间复杂度:
空间复杂度:![]()
方法一:
直接模拟
思路:直接循环遍历,输出前k个字符。![]()
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
int x;
while(cin >> s >> x){//输入
//截取前x个字符并输出
for(int i=0;i<s.size()&&x;i++,x--){
cout << s[i];
}
cout << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号