HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Given two strings, determine if one is a permutation of the other

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theonetwodeterminepermutationotherstringsgiven

Problem

After comparing my newbie attempt with other people's answers, I have a couple questions:

-
I've made s1_set the size of s1. I've seen other people assume that the strings are ASCII-256 and use s1_set(256) but to me this doesn't make sense. Won't s1_set have at most s1.size() bytes (and fewer if s1 has duplicate characters)?

-
I've also seen explicit casting before accessing s1_set: int val = static_cast(x);. Is this necessary? Is it bad form to use implicit casting?

-
Would it be preferred to use the regular for statement, or does the range-for work just as well?

`#include
#include

using namespace std;

bool is_permutation(const string& s1, const string& s2) {
if (s1.size() != s2.size()) {
return false;
}

vector s1_set(s1.size());
for (const auto& x : s1) {
++s1_set[x];
}

for (const auto& x : s2) {
if (--s1_set[x]

Solution

This code is broken.

// This creates an array with size elements all set to zero.
// But your string (in the examples) are not more than 4 long.
// So the largest vector is 4 elements long.
vector s1_set(s1.size());

// Here x is char.
for (const auto& x : s1) { 
// It is undefined if char is signed or unsigned.
// so the range of values for x is
//       0 -> 255
// or -127 -> 128
//
// Either way the range is well beyond the size of
// the array defined above.

Code Snippets

// This creates an array with size elements all set to zero.
// But your string (in the examples) are not more than 4 long.
// So the largest vector is 4 elements long.
vector<int> s1_set(s1.size());

// Here x is char.
for (const auto& x : s1) { 
// It is undefined if char is signed or unsigned.
// so the range of values for x is
//       0 -> 255
// or -127 -> 128
//
// Either way the range is well beyond the size of
// the array defined above.

Context

StackExchange Code Review Q#127738, answer score: 6

Revisions (0)

No revisions yet.