Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Lintcode13 strStr solution problem solution

Shulou Source: shulou.com Published: 2022-06-03 07:37:48 11月23日 Update

[topic description]

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.

For a given source string and a target string, you should find the first position in the source string where the target string appears (starting at 0). If it does not exist, return-1.

[topic link]

Http://www.lintcode.com/en/problem/strstr/

[topic Analysis]

Double for loops can be used to solve the string lookup problem, and the KMP algorithm is more efficient.

Source code analysis

1. Boundary check: source and target may be empty strings.

two。 Flag overflow under boundary check: pay attention to the loop judgment condition of variable I, if it is simple I < source.length (), it may overflow in the following source.charAt (I + j).

3. Code style: (1) operator = = both sides should be added spaces; (2) variable names not from such as s1``s2, be meaningful, such as target`source; (3) even if there is only one sentence in the if statement also want to increase parentheses, that is {return-1;}; (4) Java code curly braces generally on the right side of the same line, C++ code curly braces usually start another line; (5) int I, j; statement before a line of spaces, is a good code style.

4. Do not declare iQuery j in the for condition, it is easy to cause compilation errors when it is reused outside the loop.

[answer link]

Http://www.jiuzhang.com/solutions/strstr/

Tags: Character string code line parenthesis title loop variable condition space boundary link style check one sentence subscript position only right efficiency Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia macOS MariaDB Redmi Xiaomi