编程笔试题

来源:互联网 发布:多益网络运维面试经验 编辑:程序博客网 时间:2024/04/29 13:14

一道编程笔试题,判断字符串结构是否相同

判读给定了两个字符串的结构是否相同,比如:
“bool”和”pool”输出true;
“book”和”feed”输出true;
“paper”和”title”输出true;
“abcd”和”abc”输出false;

这首题乍看似曾相识,考察的是key-value 哈希的知识

bool func(char* s, char* t) {    if (s[0] == '\0' || s[0] == '\0')        return false;    unsigned int dict_s[256];    unsigned int dict_t[256];    for (int i = 0; i < 256; i++) {        dict_s[i] = dict_t[i] = 0;    }    char *p1 = s;    char *p2 = t;    int length_s=0, length_t = 0;    while (*p1 != '\0') {        length_s++;        p1++;        dict_s[*p1] += 1;    }    while (*p2 != '\0')    {        length_t++;        p2++;        dict_t[*p2] += 1;    }    if (length_s != length_t) {        return false;    }    p1 = s,p2 = t;    while (*p1 != '\0') {        if (dict_s[*(p1++)] != dict_t[*(p2++)])        {            return false;        }    }    return true;}

用C++里面的string类,可以看起来更精简一些

#include <string>bool func(const string& s, const string& t){    if (s.empty() && t.empty()) return true;    if (s.size() != t.size()) return false;    const int size = 256;     unsigned int s_cnt[size];    unsigned int t_cnt[size];    unsigned int i = 0;    for (i = 0; i<size; i++) {        s_cnt[i] = t_cnt[i] = 0;    }    for (i = 0; i < s.size(); i++) {        s_cnt[s[i]] += 1;        t_cnt[t[i]] += 1;    }    //check    for (i = 0; i < s.size(); i++) {        if (s_cnt[s[i]] != t_cnt[t[i]]) {            return false;        }    }    return true;}int main(){    char* s = "pool";    char* t = "lool";    bool aa = func(s, t);    cout << aa << endl;    system("Pause");}
原创粉丝点击