博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode算法题——求字符串中子串位置指针索引
阅读量:3958 次
发布时间:2019-05-24

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

题目

求一个字符串中,某一个子串它的下标,如果有,则返回这个子串首次出现的下标,如果没有,就返回-1

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

 

代码实现

【解一】

public class demo{		public static int strStr(String s1,String s2){				String s3 = "";		int len = 0;		int index = 0;		int result = 0;		int i = 0;		int j = 0;				if(s2.length()>s1.length()) {			return -2;		}else if(s2=="") {			return -3;		}else {			for(;i
=0){ System.out.println("该字符串出现的第一个位置为:"+(result-s2.length())); }else if(result==-3){ System.out.println("该字符串出现的第一个位置为:"+0); }else { System.out.println("请输入正确的字符串"); } }}

【解二】

public class demo{	public static void main(String[] args) {		String hayStack = "helohello";		String needle = "ello";				int pl = 0;		int index = 0;							for (int i = 0; i < hayStack.length(); i++) {			index = i;			String str = "";						for (int j = i; str.length() < needle.length(); j--) {				if (j >= 0) {					str = hayStack.charAt(j) + str;				}else {					break;				}									}			if (needle.equals(str)) {				pl = 1;				break;			}else {				pl = 0;			}		}		if (needle == "") {			System.out.println("0");		}else if (pl == 1) {			System.out.println(index+1-needle.length());		}else {			System.out.println(-1);		}	}			}

 

转载地址:http://niazi.baihongyu.com/

你可能感兴趣的文章
sql jsp
查看>>
Word生成目录
查看>>
JSP彩色验证码源程序编写
查看>>
java操作Excel、PDF文件
查看>>
java 获得系统变量
查看>>
window.event对象用法讲解
查看>>
jive license保护原理
查看>>
java des加密
查看>>
struts&hibernate&spring例子
查看>>
inno使用教程
查看>>
网吧系统母盘制作(系统分区整体考虑优化配置篇)
查看>>
spring beans beanfactory applicationcontext
查看>>
使用ORM工具进行数据访问
查看>>
使用ORM工具进行数据访问
查看>>
Quartz 使用手记 --转
查看>>
编译与部署Eclipse+Tomcat+MySQL+Liferay4.1.2
查看>>
MySQL用户授权
查看>>
mysql忘记密码怎么办?~
查看>>
MySQL修改密码方法总结
查看>>
怎么将我的硬盘屏蔽
查看>>