zoukankan      html  css  js  c++  java
  • 第 2 章 第 1 题 同位词问题 上问 数组实现

    问题分析

      输入:一个任意的单词和一个内含多个乱序单词的字典文件

      输出:该单词在字典中的所有同位词

      约束:无

    解决思路

      一一比对输入单词和字典中各个单词的标识符,如果相同则输出字典中的单词。标识符为一个内含26个整型元素数组,数组中的各个元素表示其对应的字母在其对应单词中出现的次数。比如 aabc 的标识符就是{ 2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }。

    代码实现

     1 #include <iostream>
     2 #include <fstream>
     3 #include <string>
     4 
     5 using namespace std;
     6 
     7 #define MAX 26
     8 
     9 /*
    10  * 获取单词word的标识符并存入参数数组
    11 */
    12 void getID(string word, int array[])
    13 {
    14     for (int i=0; i<MAX; i++) {
    15         array[i] = 0;
    16     }
    17     for (string::size_type i=0; i<word.length(); i++) {
    18         array[word[i]-97]++;
    19     }
    20 }
    21 
    22 /*
    23  * 比较单词的标识符
    24 */
    25 int compareID(int a[], int b[])
    26 {
    27     for (int i=0; i<MAX; i++) {
    28         if (a[i] != b[i])
    29             return 0;
    30     }
    31 
    32     return 1;
    33 }
    34         
    35 int main()
    36 {
    37     /*
    38      * a存放查询单词的标识符,b存放其比对对象单词的标识符
    39     */
    40     int a[MAX];
    41     int b[MAX];
    42 
    43     /*
    44      * 打开字典文件
    45     */
    46     string filename;
    47     cout << "请输入字典文件名( 当前目录下 ): ";
    48     cin >> filename;
    49 
    50     fstream io;
    51     io.open(filename.c_str());
    52     if (!io) {
    53         cout << "打开文件失败" << endl;
    54         return 1;
    55     }
    56 
    57     /*
    58      * 获取查询单词及其标识符
    59     */
    60     string word;
    61     cout << "请输入查询单词: ";
    62     cin >> word;
    63     getID(word, a);
    64         
    65     /*
    66      * 遍历字典文件并打印输入单词的所有同位词
    67     */
    68     string tem;
    69     cout << "单词 "" << word << "" 的同位词如下:" << endl;
    70     while (io >> tem) {
    71         getID(tem, b);
    72         if ( compareID(a, b) ){
    73             cout << tem << " ";
    74         }
    75     }
    76     cout << endl;
    77 
    78     // 关闭文件指针
    79     io.close();
    80 
    81     return 0;
    82 }

    运行测试

      测试所用字典文件:

      

      运行结果:

      

  • 相关阅读:
    在客户端模拟调用srv和topic
    直流电机测试标准
    vue项目修改host实现地址代理,实现一键登录
    小程序 日期格式化
    ES6学习笔记之async函数
    ES6学习笔记之promise
    ES6学习笔记之箭头函数
    ES6学习笔记之var,let,const
    axios post后台接收不到参数
    vue-cli2配置scss遇到的各种坑
  • 原文地址:https://www.cnblogs.com/scut-fm/p/3313599.html
Copyright © 2011-2022 走看看