Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative.
First Solution
reverse two input strings, so index and digits are the same
create a tmp int[] to store the additions of two digits multiply results
add up the array, while inserting into a stringbuilder
delete zeros in the beginning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public String multiply(String num1, String num2) {
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 see your function signature returns a char * or String, please click the reload button to reset your code definition.
Naive Solution
Two pointers:
i: from 0 to n-m, check each substring(i,i+m) equals to needle
j: from i to m+i-1, break if non-equal character found
If j=m+i after some round, then we found a substring(i, i+m) matches the needle.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
publicintstrStr(String haystack, String needle)
{
int n = haystack.length();
int m = needle.length();
//if haystack empty but needle not
if (n==0 && m!=0) return -1;
//special case
elseif(n==0||m==0) return0;
else{
for (int i = 0; i < n - m+1; i++)
{ int j=i;
for (; j < m+i; j++)
{
if (needle.charAt(j-i) != haystack.charAt(j)) break;
Given an input string, reverse the string word by word. For example, Given s = “the sky is blue”, return “blue is sky the”. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words? Reduce them to a single space in the reversed string.
Correct Solution:
First, split words into array by spaces. Then from last element in array, append to stringBuilder if not space, add one space after that element in the new string. At last, get the substring from 0 to sb.length()-1 to delete the ending space.
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Naive Sulotion
Case 1: general case, given string is a valid input, convert to int directly
Case 2: input string is null or all blank, return 0;