C++ 字符串单词分类: 数字单词与非数字单词
"思路:\n\n根据题目要求,我们需要将输入的字符串分割成单词,并将数字单词和非数字单词分类输出。\n\n首先,我们可以利用逗号和分号将字符串分割成多个子串,然后判断每个子串是否为数字单词。\n\n判断一个子串是否为数字单词的方法是,首先判断子串是否为空字符串,如果是,则不是数字单词;如果不是空字符串,则判断子串是否只包含阿拉伯数字字符,并且不包含小数点字符(小数点字符不属于阿拉伯数字字符)。\n\n然后,我们可以用两个字符串数组分别存储数字单词和非数字单词,最后将它们分别输出。\n\n算法步骤:\n\n1. 根据逗号和分号将输入的字符串分割成多个子串,存储在一个字符串数组中。\n2. 遍历字符串数组,判断每个子串是否为数字单词,将数字单词存储在一个字符串数组中,将非数字单词存储在另一个字符串数组中。\n3. 输出数字单词和非数字单词。\n\n代码实现:\n\ncpp\n#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nbool isNumberWord(const string& word) {\n if (word.empty()) {\n return false;\n }\n for (char c : word) {\n if (!isdigit(c)) {\n return false;\n }\n }\n return true;\n}\n\nint main() {\n string input;\n getline(cin, input);\n \n vector<string> words;\n string word;\n for (char c : input) {\n if (c == ',' || c == ';') {\n if (!word.empty()) {\n words.push_back(word);\n word.clear();\n }\n } else {\n word += c;\n }\n }\n if (!word.empty()) {\n words.push_back(word);\n }\n \n vector<string> numberWords;\n vector<string> nonNumberWords;\n for (const string& w : words) {\n if (isNumberWord(w)) {\n numberWords.push_back(w);\n } else {\n nonNumberWords.push_back(w);\n }\n }\n \n cout << (numberWords.empty() ? "-" : "\"") << numberWords[0];\n for (int i = 1; i < numberWords.size(); i++) {\n cout << "," << numberWords[i];\n }\n cout << "\"" << endl;\n \n cout << (nonNumberWords.empty() ? "-" : "\"") << nonNumberWords[0];\n for (int i = 1; i < nonNumberWords.size(); i++) {\n cout << "," << nonNumberWords[i];\n }\n cout << "\"" << endl;\n \n return 0;\n}\n\n\n复杂度分析:\n\n- 时间复杂度:O(n),其中n为输入字符串的长度。遍历字符串需要O(n)的时间,判断每个子串是否为数字单词需要O(1)的时间。\n- 空间复杂度:O(m),其中m为单词的个数。需要O(m)的额外空间来存储数字单词和非数字单词。\n
原文地址: https://www.cveoy.top/t/topic/p6Uu 著作权归作者所有。请勿转载和采集!