ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

C/C++ 判断str1能不能由str2里面的字符构成,如果可以,返回true;否则,返回false

2026/9/17 0:19:27 拓冰建站 浏览量
C/C++ 判断str1能不能由str2里面的字符构成,如果可以,返回true;否则,返回false

题目: 给两个字符串:str1和str2,判断str1能不能由str2里面的字符构成。
    如果可以,返回true;
    否则,返回false。

限制: str2 中的每个字符只能在str1中使用一次。

示例 1:
    输入:str1 = "a", str2 = "b"
    输出:false

示例 2:
    输入:str1 = "aa", str2 = "ab"
    输出:false

示例 3:
    输入:str1 = "aa", str2 = "aab"
    输出:true

解析1: 将str2统计到map中,在按顺序查找str1中的字符,如果能在map中找到,则每次将map中的个数减1;如果找不到则返回false;

缺点: map变量的创建,有额外的开销。

源码示例:

// Len202312.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//#include <iostream>
#include <string>
#include <map>
using namespace std;// 通过统计到map中,对比map中的个数判断结果
bool canConstruct(string str1, string str2)
{map<char, int>::iterator  iter;map<char, int> mapTag;for (int i = 0; i < str2.size(); i++){iter = mapTag.find(str2[i]);if (iter == mapTag.end()) mapTag.insert(pair<char, int>(str2[i], 1));else mapTag[str2[i]] = mapTag[str2[i]] + 1;}for (int i = 0; i < str1.size(); i++){iter = mapTag.find(str1[i]);if (iter == mapTag.end()){return false;}else{if (mapTag[str1[i]] > 0){mapTag[str1[i]] = mapTag[str1[i]] - 1;}else{return false;}}}return true;
}int main()
{string str1 = "a";string str2 = "b";bool bResult = canConstruct(str1, str2);printf("str1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));str1 = "aa";str2 = "ab";bResult = canConstruct(str1, str2);printf("\n\nstr1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));str1 = "aa";str2 = "aab";bResult = canConstruct(str1, str2);printf("\n\nstr1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));}

执行结果:

解析2: 用嵌套循环,每次查找str1中的数据的时候,遍历一次str2,如果找到,则将str2中的当前值置空,退出当前循环。如果遍历完str2还是没有找到,则返回false.

示例源码:

// Len202312.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//#include <iostream>
#include <string>
#include <map>
using namespace std;bool canConstruct(string str1, string str2)
{for (int i = 0; i < str1.size(); i++){bool bFind = false;for (int j = 0; j < str2.size(); j++){if (str2[j] == str1[i]){bFind = true;str2[j] = ' ';break;}}if (bFind == false){return false;}}return true;
}int main()
{string str1 = "a";string str2 = "b";bool bResult = canConstruct(str1, str2);printf("str1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));str1 = "aa";str2 = "ab";bResult = canConstruct(str1, str2);printf("\n\nstr1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));str1 = "aa";str2 = "aab";bResult = canConstruct(str1, str2);printf("\n\nstr1 = \"%s\", str2 = \"%s\", result = %s", str1.c_str(), str2.c_str(), (bResult != 0) ? ("true") : ("false"));}

执行结果: