zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第1章:数组和字符串——题目3

    2014-03-18 01:32

    题目:对于两个字符串,判断它们是否是Anagrams

    解法:统计俩单词字母构成是否相同即可。

    代码:

     1 // 1.3 Given two strings, write a method to decide if one is a permutation of the other.
     2 // count them.
     3 #include <cstdio>
     4 #include <cstring>
     5 using namespace std;
     6 
     7 class Solution {
     8 public:
     9     bool isPermutation(const char *s, const char *p) {
    10         if (nullptr == s || nullptr == p) {
    11             return false;
    12         }
    13 
    14         size_t len = strlen(s);
    15         if (len != strlen(p)) {
    16             return false;
    17         }
    18 
    19         int a[256];
    20         memset(a, 0, 256 * sizeof(int));
    21 
    22         size_t i;
    23         for (i = 0; i < len; ++i) {
    24             ++a[s[i]];
    25             --a[p[i]];
    26         }
    27         for (i = 0; i < 256; ++i) {
    28             if (a[i]) {
    29                 return false;
    30             }
    31         }
    32         return true;
    33     }
    34 };
    35 
    36 int main()
    37 {
    38     char s[1000], p[1000];
    39     Solution sol;
    40 
    41     while (scanf("%s%s", s, p) == 2) {
    42         printf(""%s" is ", s);
    43         if (!sol.isPermutation(s, p)) {
    44             printf("not ");
    45         }
    46         printf("a permutation of "%s".
    ", p);
    47     }
    48 
    49     return 0;
    50 }
  • 相关阅读:
    return和yield的区别
    基本装饰器
    javascript实例:两种方式实现tab栏选项卡
    javascript实例:路由的跳转
    javascript实例:点亮灯泡
    标签页QTabWidget
    主窗口QMainWindow和启动画面
    各种对话框
    列表视图QlistView
    拆分窗口QSplitter
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3606671.html
Copyright © 2011-2022 走看看