#include<iostream> #include<vector> #include<string> #include<map> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) :val(x), left(NULL), right(NULL) {} }; class IdenticalTree { public: string IntegertoStr(int m) { if(!m) return "0!"; string res; vector<int> temp; while(m) { temp.push_back(m%10); m=m/10; } for(vector<int>::reverse_iterator riter=temp.rbegin();riter!=temp.rend();riter++) res.push_back(*riter+48); res.push_back(‘!‘); return res; } void Serialize(TreeNode* root,string &res) { //#==空值 !==值的结束符 if(!root) { res+="#!"; return; } res+=IntegertoStr((*root).val); Serialize((*root).left,res); Serialize((*root).right,res); } string toString(TreeNode* root) { string res; Serialize(root,res); return res; } bool chkIdentical(TreeNode* A, TreeNode* B) { //把两个二叉树序列化字符串 string s1=toString(A),s2=toString(B); if(s1.find(s2)!=string::npos) return true; else return false; } };
#include<iostream> #include<string> #include<vector> using namespace std; class Transform { public: bool chkTransform(string A, int lena, string B, int lenb) { if(lena!=lenb) return false; int HashTable1[256]={0},HashTable2[256]={0},i; for(i=0;i<lena;i++) { HashTable1[A[i]]++; HashTable2[B[i]]++; } i=0; while((i<256)&&HashTable1[i]==HashTable2[i]) i++; if(i>=256) return true; else return false; } }; int main() { string a("abce"),b("rbca"); Transform A; bool c=A.chkTransform(a,4,b,4); cout<<c; return 0; }
#include<iostream> #include<string> #include<vector> using namespace std; //遇到字符串翻转的问题,一般都是先局部翻转然后整体翻转 class Translation { public: string stringTranslation(string A, int n, int len) { if(len>n) exit(-1); //1.先翻转0——len-1之间的字符 reverseWord(A,0,len-1); //2.再翻转len——n-1之间的字符 reverseWord(A,len,n-1); //3.然后整体翻转字符串 reverseWord(A,0,n-1); return A; } void reverseWord(string &A,int low,int high) { if(low>=high) return; char temp; while(low<high) { temp=A[low]; A[low]=A[high]; A[high]=temp; low++; high--; } } }; int main() { string a("ABCDE"); Translation A; string res=A.stringTranslation(a,5,3); cout<<res; return 0; }
#include<iostream> #include<string> #include<vector> using namespace std; class Reverse { public: string reverseSentence(string A, int n) { if(A.empty()) return ""; reverseWord(A,0,n-1); //i记录单词的第一个字符,j记录单词的最后一个字符 int i=0,j=0; while(i<n) { while(i<n&&A[i]==‘ ‘) i++; if(i>=n) return A; j=i; while(i<n&&A[i]!=‘ ‘) i++; if(i>=n) { reverseWord(A,j,n-1); return A; } reverseWord(A,j,i-1); } return A; } void reverseWord(string &A,int low,int high) { if(low>=high) return; char temp; while(low<high) { temp=A[low]; A[low]=A[high]; A[high]=temp; low++; high--; } } }; int main() { string arr("dog loves pig"); Reverse a; a.reverseSentence(arr,13); cout<<arr; return 0; }
原文:https://www.cnblogs.com/tianzeng/p/11228213.html