解法一:Brute-force int strStr(string haystack, string needle) { int m = haystack.size(); int n = needle.size(); if (!n) ; ; i < m - n + ; ++i) { ; while (j < n) { if (needle[j] == haystack[k]) { j++; k++; } else { break; } } if (j == n) return i; } ; }…
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 解题: 本题为典型的KMP算法考察题,KMP算法描述为: 设主串S,匹配串P,i为S的索引下标,j为P的索引下标,初始i和j设置为0. 在i小于S的长度和j小于P的长度时,开始循环: 1.比较S[i]和P[j]是否相同: 2.如果相同则i++,j+…
Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 暴力法,从haystack第一个字符开始查找needle. 代码如下: public class Solution { public String strStr(String haystack, String needle) { if(hays…
LeetCode第28题 Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle…
, INVALID}; int g_status; long long SubStrToInt(const char* str, bool minus) { ; : ; while (*str != '\0') { ') { num = num * + flag * (*str - '); if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000)) { num = ;…
string countAndSay(int n) { string res; ) return res; res = "; ) { int len = res.size(); int i, j; string resTmp; ; i < len; i = j) { char ch = res[i]; ; j < len; ++j) { if (ch != res[j]) break; } resTmp = resTmp + (') + ch; } res = resTmp; } r…
string addBinary(string a, string b) { int alen = a.size(); int blen = b.size(); ) return b; ) return a; ; ; ; string res; || j >= || carry > ) { ) carry += a[i--] - '; ) carry += b[j--] - '; res = ( + ') + res; //res不用逆序处理了 carry = carry / ; } retu…
本文是个人对LeetCode中字符串类型题目的总结,纯属个人感悟,若有不妥的地方,欢迎指出. 一.有关数字 1.数转换 题Interger to roman和Roman to integer这两题是罗马数字和整数之间的相互转换,首先要懂得什么是罗马数字以及相应的组数规则.LeetCode的题中给出的数字最大的是3999,.针对第一题有两种解法:第一是列举出罗马数字在个十百千上的各种情况,形成一个二维矩阵,然后对整数不停的取余.除10来确定相应的罗马数字:第二种是先列出罗马数字组成情况,然后通过从…
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 额,当然我用的就是暴力搜索来,没用到KMP之类的算法,有时间再来补上辣,代码如下: class Solution { public: int strStr(string haystack, string needle) { ; ; ; i <= h…
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02): The signature of the function had been updated to return the index instead of the pointer. If you still…