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