13. Implement strStr()
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#include<iostream>
#include<vector>
using namespace std;
int strLen(const char*str)
{
    int len=0;
    while(str[len])
        ++len;
    return len;
}
int strStr(const char *source, const char *target)
{
    // write your code here
    if(!source||!target)
        return -1;
    int sLen=strLen(source);
    int tLen=strLen(target);
    for(int i=0; i<=sLen-tLen; i++)
    {
        int j;
        for(j=0; j<tLen; j++)
            if(source[i+j] == '\0' ||source[i+j]!=target[j])
                break;
        if(j==tLen) return i;
    }
    return -1;
}
int main()
{
    int a=strStr("abcdabc","bcd");
    cout<<a<<endl;
    return 0;
}
| 1 | 
 | 
452删除链表中的元素
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29class Solution {
public:
    /**
     * @param head: a ListNode
     * @param val: An integer
     * @return: a ListNode
     */
  ListNode*  removeElements(ListNode * head, int val) {
        // write your code 
        ListNode *pre,*node;
        pre=NULL;
        node=head;
        while(node)
        {
            if(node->val==val){
                if(pre)
                    pre->next=node->next;
                else
                    head=head->next;
                  node=node->next;
            }
            else{
                pre=node;
                node=node->next;
            }
        }
        return head;
}
};