從給定句子中根據給定模式選擇單詞形成的最大字串
本文旨在實現一個程式,根據給定的模式從給定的句子中獲取按字典序排列的最大字串。
眾所周知,字串是一組以空字元“\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 程式設計程式碼以及獲取從給定句子中根據給定模式選擇單詞形成的按字典序排列的最大字串的演算法。
廣告