14. Implement STRSTR (): Searches for the first occurrence of a string in another string
Cases:
#include <stdio.h> #include <string.h>int main () { char str[] = "This was a simple string"; char * PCH; PCH = Strstr (str, "simple"); cout<< (*pch) <<endl; return 0;}
Output: S
The main consideration here is the special case.
Code:
public class Test {public static string StrStr (string origin, String needle) {int originlen = origin.length (); int Needlele n = needle.length (), if (Needlelen = = Originlen && Originlen = = 0) return "", if (Needlelen = = 0) return origin;for (i NT i = 0; i < Originlen; ++i) {if (originlen-i + 1 < Needlelen) return Null;int k = I;int j = 0;while (J < Needlelen && K < Origi nlen&& Needle.charat (j) = = Origin.charat (i)) {++j;++k;if (j = = Needlelen) return origin.substring (i);}} return null;} public static void Main (string[] args) {int[] a = {2, 7, 11, 23};}}
16. Find the insertion position: given an ordered array and a target value, if the value exists in the array, it returns its index, otherwise it returns where it should be inserted.
Cases:
[1,3,5,6], 5-2
[1,3,5,6], 2-1
[1,3,5,6], 7-4
[1,3,5,6], 0-0
Solution One: Traverse
Code:
public class Test {public static int arrpos (int[] A, int target) {if (a = = null) return 0;if (target <= a[0]) return 0;FO R (int i = 0; i < a.length-1; i++) {if (Target > A[i] && target <= a[i + 1]) {return i + 1;}} return a.length;} public static void Main (string[] args) {int[] a = {2, 7, 11, 23}; System.out.println (Arrpos (A, 223));}}
Solution 2:2 points Find
Code:
public class Test {public static int arrpos (int[] A, int target) {if (a = = NULL | | A.length = = 0) return 0;return searchinsert (A, Target, 0, a.length-1);} public static int Searchinsert (int[] A, int target, int start, int end) {int mid = (start + end)/2;if (target = = A[mid]) Return Mid;else if (Target < A[mid]) return start < mid? Searchinsert (A, Target, start, mid-1): Start;elsereturn End > Mid? Searchinsert (A, Target, mid + 1, end): (end + 1);} public static void Main (string[] args) {int[] a = {2, 7, 11, 23}; System.out.println (Arrpos (A, 223));}}
Interview 10 Big algorithm Rollup-strings and Arrays 7