题目描述
给定任意一个较短的子串,和另一个较长的字符串,判断短的字符串是否能够由长字符串中的字符构建出来,且长串中的每个字符只能用一次。
输入描述:
一行数据包括一个较短的字符串S和一个较长的字符串T,用一个空格分隔。保证1<=|S|<=|T|<=100000。
输出描述:
如果短的字符串可以由长字符串中的字符构建出来,输出字符串 “true”,否则输出字符串 “false”。
示例1
输入
复制
a b
输出
复制
false
示例2
输入
复制
fj jfiejfiejfie
输出
复制
true
排序,双指针扫一遍
string a, b;
cin >> a >> b;
sort(a.begin(), a.end()); //排序
sort(b.begin(), b.end());
int pa = 0, pb = 0;
n = a.size(), m = b.size();
while(pa<n && pb<m) { //双指针扫一遍
if(a[pa] == b[pb]) //相同一起往下指
pa ++, pb ++;
else //不同b往下指
pb ++;
}
printf("%s\n", pa==n ? "true" : "false"); //能够构造出a
完整代码
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO {
char print_f[105];
void read() { }
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K;
int main() {
#ifdef debug
freopen("test", "r", stdin);
// freopen("out_main", "w", stdout);
clock_t stime = clock();
#endif
string a, b;
cin >> a >> b;
sort(a.begin(), a.end()); //排序
sort(b.begin(), b.end());
int pa = 0, pb = 0;
n = a.size(), m = b.size();
while(pa<n && pb<m) { //双指针扫一遍
if(a[pa] == b[pb]) //相同一起往下指
pa ++, pb ++;
else //不同b往下指
pb ++;
}
printf("%s\n", pa==n ? "true" : "false"); //能够构造出a
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}