给定两个字符串问:左边的字符串是否可以从右边的字符串中选择一些字符串构成

给定两个字符串问:左边的字符串是否可以从右边的字符串中选择一些字符串构成

  给定两个字符串问:左边的字符串是否可以从右边的字符串中选择一些字符串构成。限定右边的字符串每个只能被选一次。

  例:

  canConstruct("a","b")->flase

  conConstruct("aa","ab")->false

  conConstruct("aa","aab")->true

  conConsruct("cbac","ababc")->false

#include <stdio.h>
#include <string.h>
int canConStruct(char leftStr[], char rightStr[]);
int canConStruct(char leftStr[], char rightStr[]) {
  //C语言字符串'\0'结尾
  int ls = strlen(leftStr); //左边字符个数
  int rs = strlen(rightStr);//右边字符个数
  for (int i = 0; i < ls; i++) {
    int isFound = 0; //左边字符是否在右边字符串中
    for (int j = 0; j < rs; j++) {
      if (rightStr[j] == leftStr[i]) {
        isFound = 1;
        rightStr[j] = '-';//右边被找的字符用特殊符号替代,表示被找过。
        break;
      }
    }
    //isFound =1 有出现
    //isFound =0 没有
    //如果左边有,右边没有则0
    if (!isFound) {
      return 0;
    }
  }
  return 1;

}

int main() {

  char leftStr1[] = "a", restrict1[] = "b";
  char leftStr2[] = "aa", restrict2[] = "ab";
  char leftStr3[] = "aa", restrict3[] = "aab";
  char leftStr4[] = "cbac", restrict4[] = "ababc";

  canConStruct(leftStr1, restrict1) == 1 ? printf("true\n") : printf("flase\n");
  canConStruct(leftStr2, restrict2) == 1 ? printf("true\n") : printf("flase\n");
  canConStruct(leftStr3, restrict3) == 1 ? printf("true\n") : printf("flase\n");
  canConStruct(leftStr4, restrict4) == 1 ? printf("true\n") : printf("flase\n");
  return 0;
}

1.png

点击这里复制本文地址 欢迎来到大黄鸡源码分享网
qrcode

大黄鸡源码编程网 © All Rights Reserved.  
网站备案号:闽ICP备18012015号-4
Powered by Z-BlogPHP
联系我们| 关于我们| 广告联系| 网站管理