String字符串查找
阿新 • • 發佈:2018-05-02
seq || can AS amp char index RR AI
字符串專題
- LintCode:13. Implement strStr()
題目描述:
對於一個給定的 source 字符串和一個 target 字符串,你應該在 source 字符串中找出 target 字符串出現的第一個位置(從0開始)。
如果不存在,則返回 -1。 C++實現
class Solution { public: /* * @param source: source string to be scanned. * @param target: target string containing the sequence of characters to match * @return: a index to the first occurrence of target in source, or -1 if target is not part of source. */ int strStr(const char *source, const char *target) { // write your code here if(source==NULL||target==NULL) return -1; int s_len = strlen(source); int t_len = strlen(target); int i = 0; int j = 0; while(i<s_len&&j<t_len){ if(source[i]==target[j]){ i++; j++; }else{ i = i-j+1; j = 0; } } if(j==t_len) return i-j; return -1; } };
String字符串查找