Cracking The Coding Interview 3rd -- 1.3

Given two strings, write a method to decide if one is a permutation of the other.

Summary: We need to ask the interviewer if "a" is a permute of "A" and if all possible characters are in range of ASCII for this particular problem.


Solution 1:

First, we need to compare if two strings have the same size, if different then they can't be permutations of each other. Then we could sort two strings and compare if they are equal to each other.

Time Complexity: O(nlogn). Space Complexity: n (if we copy the input strings), 1 (if we alter the originals)


Solution 2:

As we discussed in problem 1.1, we could use additional space with size 256. This idea is extremely useful for string/character operation, because it could be considered as some kind of hash map that gives us O(1) access to each possible character (of course, we need to confirm with interviewer about the possible characters, see if it follows ACSII). We count the number of occurrences of each characters and store the result in additional space.

Time Complexity: O(n). Space Complexity: O(1) (constant space requirements)


Header file

#ifndef __QUESTION_1_3_H_CHONG__
#define __QUESTION_1_3_H_CHONG__

#include <string>

using namespace std;

class Question1_3 {
public:
  bool isPermutation(string str1, string str2);
  bool isPermutation_2(string& str1, string& str2);
  int run();
};


#endif // __QUESTION_1_3_H_CHONG__

Source file

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include "Question1_3.h"

using namespace std;

bool Question1_3::isPermutation(string str1, string str2)
{
  if (str1.size()==str2.size()) {
    sort(str1.begin(), str1.end());
    sort(str2.begin(), str2.end());
    return str1==str2;
  }
  else return false;
}

bool Question1_3::isPermutation_2(string& str1, string& str2)
{
  if (str1.size()==str2.size()) {
    int cnts[256] = {0};
    for (int i=0; i<str1.size(); ++i) {
      cnts[int(str1[i])]++;
    }

    for(int i=0; i<str2.size(); ++i) {
      cnts[int(str2[i])]--;
      if (cnts[int(str2[i])]<0) {
        return false;
      }
    }

    return true;
  }
  else return false;
}

int Question1_3::run() {
  string str1 = "Hello";
  string str2 = "Heoll";
  string str3 = "Coell";
  if (isPermutation(str1, str2)) {
    cout << str2 << " is a permutation of " << str1 << endl;
  }
  if (!isPermutation_2(str3, str1)) {
    cout << str3 << " is not a permutation of " << str1 << endl;
  }

  return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值