[Careercup] 1.3 permutation string string arrangement

Source: Internet
Author: User

1.3 Given-strings, write a method to decide if one was a permutation of the other.

Given our two strings, let's determine if one is a fully arranged string for another. In Leetcode, the questions about permutation have the following lines, permutation Sequence sequence, permutations, all arranged, permutations II and next permutation the next arrangement. This problem is quite simple compared with them. Let's take a look at an O (n) solution, with the same method used for different characters in the 1.1 Unique characters of a string string, or an integer array instead of a hash table, first traversing through the characters in the S1, adding 1 to its corresponding position, and then traversing the S2 , minus 1 of its corresponding position, and if it is reduced to a negative number, it indicates that the characters of S2 and S1 are not exactly equal and return false. Returns true if the S2 traversal is complete. The code is as follows:

classSolution { Public:    BOOLIspermutation (stringS1,stringS2) {        if(S1.size ()! = S2.size ())return false; intm[ the] = {0};  for(inti =0; I < s1.size (); ++i) + +M[s1[i]];  for(inti =0; I < s2.size (); ++i) {--M[s2[i]]; if(M[s2[i]) <0)return false; }        return true; }};

Of course, if you do not consider the efficiency of the operation, you can also sort the two strings, the sorted two string if the exact equality will return true, and vice versa return false. The code is as follows:

class Solution {public:    bool ispermutation (stringstring  S2) {        ifreturnfalse;        Sort (S1.begin (), S1.end ());        Sort (S2.begin (), S2.end ());         return S1 = = s2;    }};

[Careercup] 1.3 permutation string string arrangement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.