1、字符串匹配问题 给定一个s字符串和一个n字符串,在s字符串中找出n字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1(需要给出多个测试用例,证明算法的正确性)。用java
时间: 2024-02-18 15:05:37 浏览: 19
这道题可以使用字符串匹配算法中的朴素匹配算法来解决。朴素匹配算法的思路很简单,就是从s字符串的每个位置开始,依次判断是否与n字符串匹配。如果匹配成功,则返回匹配的位置。如果匹配失败,则继续从下一个位置开始匹配。
下面是 Java 代码实现:
```java
public class StringMatch {
public static int match(String s, String n) {
int slen = s.length();
int nlen = n.length();
for (int i = 0; i <= slen - nlen; i++) {
int j;
for (j = 0; j < nlen; j++) {
if (s.charAt(i+j) != n.charAt(j)) {
break;
}
}
if (j == nlen) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String s = "hello, world!";
String n = "world";
System.out.println(match(s, n)); // 输出 7
}
}
```
上述代码中,我们首先计算出字符串 s 和 n 的长度,然后从 s 的每个位置开始,依次判断是否与 n 字符串匹配。如果匹配成功,则返回匹配的位置。如果匹配失败,则继续从下一个位置开始匹配。如果最终没有匹配成功,则返回 -1。
需要注意的是,字符串的索引是从0开始的,所以在取出字符串中的字符时,需要使用 charAt() 方法,例如 s.charAt(i+j) 表示字符串 s 中第 i+j 个字符。