美文网首页
字符串第一题

字符串第一题

作者: zhenjiechen | 来源:发表于2017-04-16 16:13 被阅读0次

题目:
Problem Statement
For a given source string and a target string, you should output the first
index(from 0) of target string in source string.
If target does not exist in source, just return -1.

Example
If source = "source" and target = "target", return -1.
If source = "abcdabcdefg" and target = "bcd", return 1.

Challenge
O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)
Clarification

Do I need to implement KMP Algorithm in a real interview?
Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure your confirm with the interviewer first.

答案一:
int strStr(char* haystack, char* needle) {
if (haystack == NULL || needle == NULL) return -1; //空字符串,错误

const int len_h = strlen(haystack);    //获取源字符串长度(strlen()函数要调用string.h头文件)
const int len_n = strlen(needle);    //获取目标字符串长度
for (int i = 0; i < len_h - len_n + 1; i++) {
    int j = 0;
    for (; j < len_n; j++) {
        if (haystack[i+j] != needle[j]) {
            break;
        }
    }
    if (j == len_n) return i;
}

return -1;

}

代码风格:

1、运算符==两边应加空格
2、变量名不要起s1``s2这类,要有意义,如target``source
3、Java 代码的大括号一般在同一行右边,C++ 代码的大括号一般另起一行
4、int i, j;`声明前有一行空格,是好的代码风格

是否在for的条件中声明i,j,这个视情况而定,如果需要在循环外再使用时,则须在外部初始化,否则没有这个必要。

相关文章

  • LeetCode第5题:longestPalindrome(C语

    上一题:LeetCode第4题:findMedianSortedArrays(C语言)写在前面,最长公共字符串是面...

  • 程序员面试金典 Chapter1 Arrays and Stri

    第一题 翻转字符串 把一个给定的字符串反转笨方法,遍历整个给定的string,将数组string[n]中的第i个...

  • LeetCode第8题: string-to-integer-a

    上一题:LeetCode第7题: reverse-integer(C语言) 思路:考察遍历字符串,需要处理好正负号...

  • Java日记2018-05-15

    第一题 把数字翻译成字符串 以12258为例分析,f(i)代表能翻译的字符串个数,i是字符串的位置,f(0)代表在...

  • 英语作业

    抄笔记5遍 阳光课堂必修七答案第6页 一遍过第31页第二题第三题 阳光课堂第20页第一题 第27页第一题

  • 第一次遇到比较正规的面试就被吊起来打,记录一下

    进去先是手写一个小时的算法题,第一题是不用java String.split切割字符串,我没写当初想的是字符串分成...

  • VBA第十讲练习题解析

    VBA 第十讲练习题 第一题 背景知识 val函数的参数是字符串,格式为 val(字符串) 我对这函数的理解是:他...

  • 字符串dfs

    第一题 牛客网寒训第四场 #I--回文串 题目描述 自从 Applese 学会了字符串之后,精通各种字符串算法,比...

  • Java中String类的常见面试题

    第一题:==与equals()的区别 第二题:String字符串与BufferString的传递问题 第三题:In...

  • Python练手题,敢来挑战吗?

    第一题 这到题用到了字符串的所有字母大写和所有字母小写和字符串拼接,复制,用到的函数有 json将列表中的内容按照...

网友评论

      本文标题:字符串第一题

      本文链接:https://www.haomeiwen.com/subject/mfmaattx.html