PAT1050 String Subtraction (20分) 用数组即可

题目

Given two strings S​1​​ and S​2​​ , S=S​1​​ −S​2​​ is defined to be the remaining string after taking all the characters in S​2​​ from S​1​​ . Your task is simply to calculate S1​​​ −S​2​​ for any given strings. However, it might not be that simple to do it fast.

Input Specification:
Each input file contains one test case. Each case consists of two lines which gives S​1​​ and S​2​​ , respectively. The string lengths of both strings are no more than 10​4​​ . It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.

Output Specification:
For each test case, print S​1​​ −S​2​​ in one line.

Sample Input:

They are students.
aeiou

Sample Output:

Thy r stdnts.

解析

  • 所谓 s1 - s2 就是从s1中去除出现在s2中的字符,输出剩余部分。

  • 所以可以逐个判断s1的字符,判断其是否在s2中出现,若未出现则输出,否则跳过即可。

  • 为了操作简单,使用一个布尔数组flag[256]ascii字符也就是0-255,所以遍历一次s2,将flag[s2[i]]设置为true即表示当前字符在s2中出现过。

代码

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

int main() {
    string s1, s2;
    // 原字符串中包含空格,使用getline
    getline(cin, s1);
    getline(cin, s2);
    int len1 = s1.length(), len2 = s2.length();
    bool flag[256] = {false};
    // 在s2中出现的字符,在s1中剔除
    for (int i = 0; i < len2; ++i) flag[s2[i]] = true;
    // 逐个字符判断,若未在s2中出现则输出
    for (int i = 0; i < len1; ++ i)
        if (!flag[s1[i]]) cout << s1[i];
    return 0;
}
### 使用 NumPy 创建和操作数组 #### 导入 NumPy 库 为了使用 NumPy 的功能,首先需要导入该库: ```python import numpy as np ``` #### 创建一维数组 可以利用 `np.array()` 函数来创建基于现有列表的一维数组[^2]。 ```python one_d_array = np.array([1, 2, 3]) print(one_d_array) ``` #### 切片操作 对于切片操作而言,NumPy 数组的行为与 Python 列表相似。可以通过指定起始索引、结束索引以及步长来进行切片[^1]。 ```python sliced_array = one_d_array[0:2] print(sliced_array) ``` #### 创建二维数组 通过定义形状参数 `[行数, 列数]` 可以轻松构建填充特定值的多维数组。例如,创建全为零或全为一的矩阵[^3]。 ```python two_d_zeros = np.zeros([3, 5]) # 创建一个3×5的零矩阵 two_d_ones = np.ones([10, 10]) # 创建一个110的单位矩阵 print(two_d_zeros) print(two_d_ones) ``` #### 修改单个元素 访问并修改某个具体位置上的数值非常直观,只需提供行列坐标即可完成更新。 ```python index_i = 2 index_j = 4 two_d_ones[index_i, index_j] += 5 print(two_d_ones) ``` #### 执行算术运算 支持对相同大小的两个或多于两个数组执行逐项加法、减法、乘法及除法等基本数学计算。 ```python another_two_d = np.ones([10, 10]) addition_result = two_d_ones + another_two_d # 加法 subtraction_result = two_d_ones - another_two_d # 减法 multiplication_result = two_d_ones * another_two_d # 乘法 division_result = two_d_ones / (another_two_d + 0.1) # 避免除以零的情况 print(addition_result) print(subtraction_result) print(multiplication_result) print(division_result) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值