0

I am designing a problem in which I want to find how many times a given string can be found (formed) from another base string with one character used only once.

Suppose I have

string str = "COMPUTER";

string basestr = "**TER** WITH **R** LABEL **COMPUTER** BELONGS TO **COMPUT** QUICK CUTE **COM** FOX JUM **P** S **U** R **T** H **E** LAZY DOG";

So want that my program returns 3 for this sting basestr. Here one COMPUTER is clearly available, another is in two words and last is in words and characters.

Please help me program this ? How can I do that ? Thanks

2
  • So it is more like comparing sets of chars where the order is not important, correct? Commented Jan 22, 2012 at 1:35
  • @alexm : order is not important but you need to go from position 0 to n repeatedly one by one till noting is left; Commented Jan 22, 2012 at 1:39

1 Answer 1

3

First, construct character counts for the short string. Then construct character counts for the long string. For each character count of the short string, divide the count from the long string by the count of the short string, keeping only the integer part. Pick the smallest integer - it is the answer to your problem.

int[] Count(string s) {
    int[] res = new int[256];
    foreach (var c in s) {
        res[c]++;
    }
    return res;
}
int ShortInLong(string ss, string ls) {
    var sc = Count(ss);
    var lc = Count(ls);
    int res = int.MaxValue;
    foreach (var c in ss) {
        int d = lc[c] / sc[c]; // sc[c] is never 0 because of the way we constructed it
        res = Math.Min(res, d);
    }
    return res;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Might want to return something in Count
@Walkerneo Thanks! There's only one thing to return from it, conveniently named res for result :)
There may be times when we don't have any str present in basestring. Then what ? and can you tell who to delete a completely founded word so that we don't count it again
@ItsLockedOut When the short string components cannot be found in the long string, the code would return zero. The algorithm is going to return an unexpected value when the short string is empty: you'll get int.MaxValue, which kind of makes sense: there's an infinite number of empty strings in any string. Since the algorithm does not count words directly, you do not need to delete them from the long string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.