4 两个排序数组的中位数
1 class Solution { 2 public: 3 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 4 int n=nums1.size(),m=nums2.size(); 5 if(n>m){ 6 swap(n,m); 7 swap(nums1,nums2); 8 } 9 int l=0,r=n,mid1=0,mid2=0; 10 while(l<=r){ 11 mid1=(l+r)>>1; 12 mid2=((n+m+1)>>1)-mid1; 13 if((mid1==0||mid2==m||nums1[mid1-1]<=nums2[mid2])&&(mid1==n||mid2==0||nums2[mid2-1]<=nums1[mid1])) break; 14 else if((mid1>0&&mid2<m&&nums1[mid1-1]>nums2[mid2])){ 15 r=mid1-1; 16 }else if(mid1<n&&mid2>0&&nums2[mid2-1]>nums1[mid1]){ 17 l=mid1+1; 18 } 19 } 20 cout<<"l r: "<<l<<' '<<r<<endl; 21 cout<<"mid1 mid2: "<<mid1<<' '<<mid2<<endl; 22 int maxL=0,minR=0; 23 if(mid1==0) maxL=nums2[mid2-1]; 24 else if(mid2==0) maxL=nums1[mid1-1]; 25 else maxL=max(nums1[mid1-1],nums2[mid2-1]); 26 if(mid1==n) minR=nums2[mid2]; 27 else if(mid2==m) minR=nums1[mid1]; 28 else minR=min(nums1[mid1],nums2[mid2]); 29 cout<<maxL<<' '<<minR<<endl; 30 if((n+m)%2==0) return (maxL+minR)/2.0; 31 else return maxL; 32 } 33 };
5 最长回文字串
1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 string str="$+"; 5 for(int i=0;i<s.length();i++){ 6 str+=s[i]; 7 str+="+"; 8 } 9 str+="%"; 10 s=str; 11 cout<<s<<endl; 12 int maxl=0,n=s.length(),id=0,mx=0,d[2009]; 13 string ans=""; 14 memset(d,0,sizeof(d)); 15 for(int i=1;i<n;i++){ 16 if(i<mx){ 17 d[i]=min(mx-i,d[2*id-i]); 18 }else{ 19 d[i]=1; 20 } 21 while(s[i-d[i]]==s[i+d[i]]) d[i]++; 22 if(mx<i+d[i]){ 23 mx=i+d[i]; 24 id=i; 25 } 26 if(d[i]-1>maxl){ 27 maxl=d[i]-1; 28 ans=""; 29 for(int j=i-d[i]+1;j<=i+d[i]-1;j++){ 30 if(s[j]!='+') ans+=s[j]; 31 } 32 } 33 } 34 return ans; 35 } 36 };
10 正则表达式匹配
1 class Solution { 2 public: 3 bool isMatch(string s, string p) { 4 int n=s.length(),m=p.length(); 5 if(n==0&&m==0) return 1; 6 if(n==1&&m==1) return s[0]==p[0]||p[0]=='.'; 7 if(p[1]!='*'){ 8 if(n==0) return 0; 9 if(p[0]==s[0]||p[0]=='.') return isMatch(s.substr(1),p.substr(1)); 10 else return 0; 11 } 12 while(!s.empty()&&(s[0]==p[0]||p[0]=='.')){ 13 if(isMatch(s,p.substr(2))) return 1; 14 s=s.substr(1); 15 } 16 return p.length()>=2?isMatch(s,p.substr(2)):0; 17 } 18 };