LintCode 字符串查找
生活随笔
收集整理的這篇文章主要介紹了
LintCode 字符串查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對于一個給定的 source 字符串和一個 target 字符串,你應該在 source 字符串中找出 target 字符串出現的第一個位置(從0開始)。如果不存在,則返回?-1。
說明在面試中我是否需要實現KMP算法?
- 不需要,當這種問題出現在面試中時,面試官很可能只是想要測試一下你的基礎應用能力。當然你需要先跟面試官確認清楚要怎么實現這個題。
如果 source =?"source"?和 target =?"target",返回?-1。
如果 source =?"abcdabcdefg"?和 target =?"bcd",返回?1。
class Solution { public:/*** Returns a index to the first occurrence of target in source,* or -1 if target is not part of source.* @param source string to be scanned.* @param target string containing the sequence of characters to match.*/int strStr(const char *source, const char *target) {// write your code hereif(source==NULL||target==NULL)return -1;if(*target=='\0')//查找的是空串return 0;int i=0;int j=-1;while(*source!='\0'){j++;if(*source==*target)//找首字母相同的{i=j;const char *p=source;//用兩個指針const char *q=target;while(*p==*q){if(*(q+1)=='\0')return i;else {p++;q++;}}}source++;}return -1;} };
轉載于:https://www.cnblogs.com/lelelelele/p/6135741.html
總結
以上是生活随笔為你收集整理的LintCode 字符串查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用ssh-copy-id复制公钥到多台
- 下一篇: mysql中使用concat例子