题解 | #截取字符串#

截取字符串

https://www.nowcoder.com/practice/a30bbc1a0aca4c27b86dd88868de4a4a

解题思路

  1. 题目要求输入一个字符串和一个整数 ,截取字符串的前 个字符
  2. 需要注意输入的字符串长度 满足 ,且
  3. 这是一个简单的字符串截取问题,可以直接使用语言内置的字符串截取函数或循环遍历前 个字符

代码

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    int k;
    cin >> str >> k;
    cout << str.substr(0, k) << endl;
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int k = sc.nextInt();
        System.out.println(str.substring(0, k));
    }
}
s = input()
k = int(input())
print(s[:k])

算法及复杂度

  • 算法:直接使用字符串截取
  • 时间复杂度: - 需要遍历前 个字符
  • 空间复杂度: - 需要存储长度为 的结果字符串
全部评论

相关推荐

葬爱~冷少:我当时都是上午刷力扣,下午背八股,有活给我先别急,没活就干自己的事情
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务