28. Implement strStr()

网友投稿 641 2022-11-11

28. Implement strStr()

28. Implement strStr()

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= 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; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:IDEA中将SpringBoot项目提交到git仓库的方法步骤
下一篇:165. Compare Version Numbers
相关文章

 发表评论

暂时没有评论,来抢沙发吧~