10 algorithm questions for interviews-string and array 7, algorithm Array
14. Implement strStr (): Search for the first position of a string in another string
Example:
#include <stdio.h>#include <string.h>int main (){ char str[] ="This is a simple string"; char * pch; pch = strstr (str,"simple"); cout<<(*pch)<<endl; return 0;}
Output: s
Special cases should be considered here.
Code:
public class test {public static String strStr(String origin, String needle) {int originLen = origin.length();int needleLen = needle.length();if (needleLen == originLen && originLen == 0)return "";if (needleLen == 0)return origin;for (int i = 0; i < originLen; ++i) {if (originLen - i + 1 < needleLen)return null;int k = i;int j = 0;while (j < needleLen && k < originLen&& 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. Looking for the insert position: given an ordered array and a target value, if the value exists in the array, its index is returned; otherwise, its inserted position is returned.
Example:
[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 1: traverse
Code:
public class test {public static int arrPos(int[] A, int target) {if (A == null)return 0;if (target <= A[0])return 0;for (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: Binary Search
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));}}