Determine if A is permutation of B using ASCII values

前端 未结 3 1092
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-22 02:40

I wrote an function to determine if string a is a permutation of string b. The definition is as follows:

bool isPermutation(std::string         


        
3条回答
  •  青春惊慌失措
    2021-01-22 03:21

    std::sort( strOne.begin(), strOne.end() );
    std::sort( strTwo.begin(), strTwo.end() );    
    return strOne == strTwo;
    

    will be sufficient.


    My suggestion is to use std::unordered_map

    i.e.

    std::unordered_map< char, unsigned > umapOne;
    std::unordered_map< char, unsigned > umapTwo;
    for( char c : strOne ) ++umapOne[c];
    for( char c : strTwo ) ++umapTwo[c];
    return umapOne == umapTwo;
    

    As an optimization you can add at the top for a solution

    if( strOne.size() != strTwo.size() ) return false;
    

    Better std::unordered_map solution,

    if( strOne.size() != strTwo.size() ) return false; // required
    std::unordered_map< char, int > umap;
    for( char c : strOne ) ++umap[c];
    for( char c : strTwo ) if( --umap[c] < 0 )  return false;
    return true;
    

    If you need to just solve a problem without knowing how to do it, you may use std::is_permutation

    return std::is_permutation( strOne.begin(), strOne.end(), strTwo.begin(), strTwo.end() );
    

提交回复
热议问题