11.String to int, which is atoi function implementation.
The main considerations are as follows:
1. String is empty
2. There are non-numeric characters in string, such as white space characters, ABCD, etc.
3. The positive or negative string
Code:
public class Test {public static int atoi (String str) {if (str = = NULL | | str.length () < 1) return 0;STR = Str.trim (); ch AR flag = ' + '; int i = 0;if (Str.charat (0) = = '-' | | Str.charat (0) = = ' + ') {++i;flag = Str.charat (0);} Double result = 0;int J = i;while (Str.length () > J) {if (Str.charat (j) < ' 0 ' | | str.charat (i) > ' 9 ') {System.err . println ("Bad Input"); return integer.min_value;} ++j;} while (Str.length () > I && str.charat (i) > ' 0 ' && str.charat (i) < ' 9 ') {result = result * + (s Tr.charat (i)-' 0 '); ++i;} if (flag = = '-') result =-result;if (Result > Integer.max_value) return integer.max_value;if (Result < Integer.min_va LUE) return Integer.min_value;return (int) result; public static void Main (string[] args) {int i = atoi ("1+2"); int j = atoi ("55"); System.out.println ("I:" + i + ", J:" + j);}}
12. Merging ordered arrays
Given two arrays A and B, B is combined into a
Code:
public void merge (int a[], int m, int. b[], int n) {int i = M-1;int j = N-1;int k = m + n-1; while (k >= 0) {if (j < 0 | | (I >= 0 && a[i] > B[j])) a[k--] = a[i--];elsea[k--] = b[j--];}}
13. Matching Brackets
Given a string containing ' (', ') ', ' {', '} ', ' [' and '] ', determine if the parentheses match
Brace matching requires stack, and map determines if the match
Code:
Import Java.util.hashmap;import Java.util.stack;public class Test {public static Boolean bvalid (String s) {hashmap< Character, character> map = new Hashmap<character, character> (), Map.put (' (', ') '), Map.put (' [', '] '); Map.put (' {', '}'); stack<character> stack = new stack<character> (); for (int i = 0; i < s.length (); i++) {Char Curr = S.charat ( i); if (Map.keyset () contains (Curr)) {Stack.push (curr);} else if (Map.values (). Contains (Curr)) {if (!stack.empty () && Map.get (Stack.peek ()) = = Curr) {Stack.pop ();} else {return false;}}} return Stack.empty ();} public static void Main (string[] args) {System.out.println (Bvalid ("{()}"));}}
Interview 10 Big algorithm Rollup-strings and Arrays 6