从给定句子中根据给定模式选择单词形成的最大字符串


本文旨在实现一个程序,根据给定的模式从给定的句子中获取按字典序排列的最大字符串。

众所周知,字符串是一组以空字符“\0”结尾的字符,在 C 编程中。C 字符串中的字符保存在字符数组中。字符串和字符数组之间的主要区别在于,C 字符串与字符数组的区别在于它以独特的字符“\0”结尾。

示例 1

Input: S = “slow and steady”, B = “sdfh”
Output: steady

示例 2

Input: S = “an apple a day”, B = “sod”
Output: day

示例 3

Input: S = “together we stand”, B = “thfd”
Output: together stand

示例 4

Input: S = “let us learn programming”, B = “legh”
Output: let learn programming

问题陈述

实现一个程序,根据给定的模式从给定的句子中获取按字典序排列的最大字符串。

方法

当只有一个字符可用时,确定它是否已按字典序升序排列,如果是,则将该字符添加到输出字符串中。当字符串 S 的一个单词中存在两个字符时,将它们添加到输出字符串中。将输出字符串组织成字典序最大的排列。

算法

实现一个程序以获取从给定句子中根据给定模式选择单词形成的按字典序排列的最大字符串的算法如下:

  • 步骤 1 − 定义一个字符串。

  • 步骤 2 − 检查字符串是已排序还是未排序。

  • 步骤 3 − 实现一个函数以获取按字典序排列的最大字符串。

  • 步骤 4 − 统计字符串中所有字符的频率。

  • 步骤 5 − 现在,遍历给定的句子。

  • 步骤 6 − 保存对应于提供的条件的输出

  • 步骤 7 − 打印输出作为结果。

示例(C 程序)

这是上述算法的 C 程序实现,用于获取从给定句子中根据给定模式选择单词形成的按字典序排列的最大字符串。

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_STR_LEN 100
bool is_sorted(char s[]){
   int len = strlen(s);
   for (int i = 0; i < len - 1; i++) {
      if (s[i] > s[i + 1])
         return false;
   }
   return true;
}
void choose_str(char s[], char b[], int n) {
   int char_count[256] = {0};
   char *token;
   char *rest = s;
   for (int i = 0; b[i]; i++) {
      char_count[b[i]]++;
   }
   int g = strlen(b) / 2;
   int c;
   char *result[MAX_STR_LEN] = {0};
   int result_count = 0;
   while ((token = strtok_r(rest, " ", &rest))) {
      c = 0;
      int len = strlen(token);
      for (int j = 0; j < len; j++){
         if (char_count[token[j]])
            c++;
         if (c == g)
            break;
      }
      if ((c == 1 && is_sorted(token)) || c == g) {
         result[result_count] = token;
         result_count++;
      }
   }
   for (int i = 0; i < result_count; i++) {
      printf("%s ", result[i]);
   }
   printf("
"); } int main(){ char S[MAX_STR_LEN] = "slow and steady"; char B[MAX_STR_LEN] = "sdfh"; choose_str(S, B, sizeof(S) / sizeof(S[0])); return 0; }

输出

执行后,它将产生以下输出:

steady

结论

同样,我们可以实现一个程序来获取从给定句子中根据给定模式选择单词形成的按字典序排列的最大字符串。本文解决了获取程序以查找从给定句子中根据给定模式选择单词形成的按字典序排列的最大字符串的挑战。

这里提供了 C 编程代码以及获取从给定句子中根据给定模式选择单词形成的按字典序排列的最大字符串的算法。

更新于: 2023-10-31

161 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.