算法复习:字符串
手撕字符串复制
char * strcppy(char * dest,const char *src,size_t count) { char *tmp = dest; while (count-- && (*dest++ = *src++) != '\0'); return tmp; }
c++常用string操作:
#include<algorithm>
reverse(s.begin(),s.end()); //字符串反转
string result=s.substr(pos, n); //截取字符串s从pos开始的n个
string result=s.substr(pos) ; //截取从pos开始到最后的字符串
strcpy (str2,str1); //把str1复制给str2
int result=strcmp(str1,str2); //比较str1和str2 result<0则str1小
leetcode 5. 最长回文子串
输入串s,串s的反转串t,题目转化为求s和t最长连续子串,
但是有一个限制条件是找到的这个回文串 在t中的位置折合回s应该能对应才行,反例:"aacdefcaa" 用最长连续子串找到的是aac,而aac不符合题意
#include<algorithm> class Solution { public: string longestPalindrome(string s) { string t=s; if(s.size()<1) return s; reverse(t.begin(),t.end()); int size=s.size(); int lb_i,lb_j,maxl=0;//用于保存取到最大长度时的位置 vector<vector<int> >dp(size,vector<int>(size,0)); for(int i=0;i<size;i++)//初始化 { if(s[i]==t[0]) { dp[i][0]=1; maxl=1;lb_i=i;lb_j=0; } if(s[0]==t[i]) { dp[0][i]=1; maxl=1;lb_i=0;lb_j=i; } } for(int i=1;i<size;i++) { char A=s[i]; for(int j=1;j<size;j++) { char B=t[j]; if(A==B) { dp[i][j]=dp[i-1][j-1]+1; if(dp[i][j]>maxl) { int pre=size-1-j;//找回原来位置,用于对比是否匹配 pre=pre+dp[i][j]-1; if(pre!=i)//位置不对应的不算 "aacdefcaa" 排除aac continue; maxl=dp[i][j];lb_i=i;lb_j=j; } } } } /*for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { cout<<dp[i][j]<<" "; } cout<<endl; } cout<<lb_i<<" "<<size-(lb_j+1-maxl)<<" "<<maxl;*/ return s.substr(lb_i-maxl+1,maxl); } };
面试题58 - I. 翻转单词顺序
class Solution { public: void exchange(int head,int tail,string &s) { char tmp; while(head<tail) { tmp=s[head]; s[head]=s[tail]; s[tail]=tmp; head++; tail--; } return; } string deal(string s) { if(s=="") return s; string::iterator it=s.begin(); while(*it==' ') { if(s.size()==1) return ""; it=s.erase(it); } it=s.begin(); char last=*it; it++; for(;it!=s.end();it++) { if(last==' '&&*it==' ') { it=s.erase(it); it--; } else { last=*it; } } return s; } string reverseWords(string s) { s=deal(s); int size=s.size(),head=0,tail=size-1,lable=0; exchange(head,tail,s); for(int i=0;i<size;i++) { if(lable==0&&s[i]!=' ') { head=i; lable=1; } if(lable==1&&(s[i]==' '||i==size-1)) { tail=i-1; lable=0; if(i==size-1) exchange(head,tail+1,s); else exchange(head,tail,s); } } return deal(s); } };
面试题58 - II. 左旋转字符串
class Solution { public: void exchange(int head,int tail,string &s) { char tmp; while(head<tail) { tmp=s[head]; s[head]=s[tail]; s[tail]=tmp; head++; tail--; } return; } string reverseLeftWords(string s, int n) { int size=s.size(),head=0,tail=size-1; exchange(head,tail,s); exchange(tail-n+1,tail,s); exchange(head,tail-n,s); return s; } };