另一个布尔函数中的一个字符

One char from the other bool function

本文关键字:一个 字符 布尔 函数 另一个      更新时间:2023-10-16

我想要一个函数,当且仅当可以通过简单地划掉某些字母从char* t获得char* s时,它才会返回true,例如g("ERT", "EAARYT")=trueg("ERT","ABCT")=false.

我对这段代码的想法如下:

bool g(char* s, char* t) {
for (int i=0; s[i]!=0;i++) {
for (int j=i; t[j]!=0; j++) {
if (s[i]==t[j]) {
return true;
}
}
}
return false;
}

显然它不起作用,因为它只检查第一个字母是否存在,然后立即返回 true。 我应该如何改变它?

我更喜欢使用嵌套循环/如果构造,这应该是可行的。

当且仅当可以通过简单地划掉某些字母从char *t获得char *s时返回true。这意味着两件事:

  • [A]t应包含s的所有字符。因此,我们需要存储字符数。
  • [B]t应包含s的所有字符,以及t应具有与s相同的常用字符。

解决方案 A:t中字符的顺序无关紧要。重要的是s中的所有角色都应该出现在t中。

g("ERRT", "ERT") = false

g("ERRR", "ERRT") = false

g("ERRR", "RRRE") = true

bool g(char* s, char* t) 
{
int hash[256] = {0};
int i;
for(i = 0; t[i]; ++i) 
{
hash[t[i]] += 1;
}
for(i = 0; s[i]; ++i) 
{
if(hash[s[i]] <= 0)
{
return false;
}
else
{
hash[s[i]] -= 1;
}
}
return true;
}

解决方案 B:t中的字符顺序确实很重要。此外,s中的所有字符都应出现在t中。

g("ERRT", "RERT") = false

g("ERRR", "RRER") = false

g("ERRR", "RRRE") = false

g(">ERTR", "RERGRTBR") = TRUE

bool g(char* s, char* t) 
{
if(strcmp(LCS(s, t), s) == 0)
{
return true;
}
return false;
}    

其中,LCS(s, t) =最长的公共子序列

如果没有找到后者,您可以返回false,否则成功:

bool g(const char* s, const char* t) {
for (int i = 0; s[i] != 0; i++) {
bool found = false;
for (int j = i; t[j] != 0; j++) {
if (s[i] == t[j]) {
found = true;
}
}
if (!found) {
return false;
}
}
return true;
}

此外,请考虑使用strspn对匹配字符进行计数

bool g(const char* s, const char* t){
return strspn(s, t) == strlen(s);
}

你可以这样做-

bool g(char* s, char* t){
int sLen=strlen(s);
int tLen=strlen(t);
if(sLen > tLen)
{
return false;
}
int j=0;
for(int i=0;i<tLen;i++)
{
if(s[j] == t[i])
{
j++;
}
if(j == sLen)
{
return true;
}
}
return false;
}

试试这个:

int c = 0;
int len = strlen(s); // Find the length of string
for(i=0; s[i]!=0;i++)
{
for(j=0; t[j]!=0; j++)
{
if(s[i]==t[j])
{
c++; // count the character, If count is equal to length then true.
}
}
}
if (len == c) 
return true;
else
return false;

我将仅使用一个循环编写函数,并将第二个循环替换为标准 C 函数strchr。例如

#include <iostream>
#include <iomanip>
#include <cstring>
bool g( const char *s, const char *t )
{
size_t m = std::strlen( s );
size_t n = std::strlen( t );
const char *p;
while ( ( m != 0 ) and not ( n < m ) and ( p = std::strchr( t, s[0] ) ) )
{
++p;
n -= p - t;
t = p;
--m;
++s; 
}
return m == 0;
}
int main() 
{
std::cout << "g( "ERT", "EAARYT" ) = " 
<< std::boolalpha << g( "ERT", "EAARYT" ) << std::endl;       
std::cout << "g( "ERT", "ABCT" ) = " 
<< std::boolalpha << g( "ERT", "ABCT" ) << std::endl;     
}

程序输出为

g( "ERT", "EAARYT" ) = true
g( "ERT", "ABCT" ) = false
相关文章: