面试3之确定其中一个字符串的字符重新排列后,能否变成另一个字符串

    xiaoxiao2021-04-17  54

    题目描述 给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。 给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。 测试样例: "This is nowcoder","is This nowcoder" 返回:true "Here you are","Are you here"

    返回:false

    #include<iostream> using namespace std; #include<string> #include<algorithm> //意思理解错了,这道题的意思是所有的字符重排列,不是单词重排列,这个函数写的是单词的重排列 /* bool CheckSam(string stringA,string stringB) { if (stringA.length() != stringB.length()) return false; string str1[5000]; string str2[5000]; int i = 0; int j = 0; size_t idx1 = 0; size_t idx2 = stringA.find(' '); while (idx2 != string::npos) { str1[i++] = stringA.substr(idx1,idx2-idx1); idx1 = idx2+1; idx2 = stringA.find(' ',idx1); } str1[i++] = stringA.substr(idx1); idx1 = 0; idx2 = stringB.find(' '); while (idx2 != string::npos) { str2[j++] = stringB.substr(idx1,idx2-idx1); idx1 = idx2+1; idx2 = stringB.find(' ',idx1); } str2[j++] = stringB.substr(idx1); for (int len1 = 0; len1 < i; ++len1) { int len2 = 0; for( len2 = 0; len2 < j; ++len2) { if (str1[len1] ==str2[len2]) break; } if (len2 == j) return false; } return true; } */ //方式一,时间复杂度O(n) /* bool CheckSam(string stringA,string stringB) { if (stringA.length() != stringB.length()) return false; unsigned char array1[256] = { 0 } ; unsigned char array2[256] = { 0 } ; for (size_t i = 0; i < stringA.length(); ++i) { array1[ stringA[i] ]++; } for (size_t j = 0; j < stringB.length(); ++j) { array2[ stringB[j] ]++; } for (size_t idx = 0; idx < 256; ++idx) { if (array1[idx] != array2[idx]) return false; } return true; } */ //方式二,时间复杂度O(nlongn) bool CheckSam(string stringA,string stringB) { if (stringA.length() != stringB.length()) return false; sort(stringA.begin(),stringA.end()); sort(stringB.begin(),stringB.end()); for(size_t i = 0; i < stringA.length(); ++i) { if (stringA[i] != stringB[i]) return false; } return true; } int main() { string stringA = "This is nowcoder"; string stringB = "is This nowcoder"; cout << CheckSam(stringA,stringB) <<endl;; cout << "hello..." <<endl; return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-674241.html

    最新回复(0)