Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

public class Solution {
public int strStr(String haystack, String needle) {
for (int i = 0;; i++) {
for (int j = 0;; j++) {
if (j == needle.length())
return i;
if (i + j == haystack.length())
return -1;
if (needle.charAt(j) != haystack.charAt(i + j))
break;
}
}
}
}
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0 || needle == null || haystack.equals(needle)) return 0;
if(haystack.length() < needle.length() || !haystack.contains(needle)) return -1;

int i = 0;
while(i<haystack.length()){

int aindex = i;
int j = 0;

while(j<needle.length()){
char a = haystack.charAt(aindex);
char b = needle.charAt(j);
if(a==b){
aindex++;
j++;
}
else{
break;
}
if(j >= needle.length())
return i;
}
i++;
}
return -1;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode node = new ListNode();
ListNode root = node;
while(l1!=null && l2!=null) {
if(l1.val <= l2.val)
{
node.next = l1;
l1 = l1.next;
} else {
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if(l1 == null)
node.next = l2;
if(l2 == null)
node.next = l1;

return root.next;
}
}