博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Implement_strStr --leetcode
阅读量:6947 次
发布时间:2019-06-27

本文共 1727 字,大约阅读时间需要 5 分钟。

hot3.png

package com.helloxin.leetcode.algorithms;/** * 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 */import java.util.regex.Matcher;import java.util.regex.Pattern;/** * create by nandiexin on 2017/12/19 **/public class Implement_strStr {    /**     * 假如使用 string 的函数     * @param haystack     * @param needle     * @return     */    public static int strStr(String haystack, String needle) {           return haystack.indexOf(needle) ;    }    /**     * 用两个for循环 去解决问题  如果字符串长了  要匹配多久呢?     * @param haystack     * @param needle     * @return     */    public static int strStr2(String haystack, String needle) {        int m = haystack.length(), n = needle.length();        if (m < n) {            return -1;        }        for (int i = 0; i <= m - n; ++i) {            int j = 0;            for (j = 0; j < n; ++j) {                if (haystack.charAt(i + j) != needle.charAt(j)){                    break;                }            }            if (j == n) {                return i;            }        }        return -1;    }    /**     * 然后就可以用正则表达式啦  当然正则这个包在leetcode是通不过的哈     * @param haystack     * @param needle     * @return     */    public static int strStr3(String haystack, String needle){        Pattern p = Pattern.compile(needle);        Matcher m = p.matcher(haystack);        while(m.find()) {           return m.start();        }        return -1;    }    public static void main(String[] args) {        System.out.println(strStr3("hello","lp"));    }}

转载于:https://my.oschina.net/u/2277632/blog/1591971

你可能感兴趣的文章
android发送短信验证码并自动获取验证码填充文本框
查看>>
App 是否真的能检测手机壳颜色?
查看>>
学Hadoop还是Spark好?
查看>>
微服务生命周期的9个任务事项
查看>>
实战Kafka ACL机制
查看>>
云监控服务使用教程
查看>>
“旧城改造”的背后——银泰新零售阿里云解决方案(上)
查看>>
java B2B2C源码电子商务平台 -SpringCloud服务相互调用RestTemplate
查看>>
java B2B2C Springcloud电子商务平台源码-zuul 过滤器机制
查看>>
分布式消息系统:Kafka
查看>>
我的友情链接
查看>>
H3C防火墙路由器做回流
查看>>
Tableau10.5视频课程之常见图形制作
查看>>
Kettle5.4实战项目培训课程
查看>>
获取局域网里一个MAC地址对于的IP地址
查看>>
让phpmailer支持中文名称的附件和邮件标题中文乱码(转)
查看>>
JavaScript强化教程——JavaScript Math(算数) 对象
查看>>
CentOS7部署Kubernetes集群
查看>>
struts2中使用DMI(动态调用方法)方式配置action
查看>>
使用hyperpacer实现AWR报告的同步收集
查看>>