1.给你一个字符串数组(每个字符审均由小写字母组成)和一个字符规律(由小写字母和,和“组成),识别数组中哪些字符串可以匹配到字符规律上。 2.“.”匹配任意单个字符,“*”匹配零个或多个前面的那一个元素,所谓匹配,是要涵盖整个字符串的,而不是部分字符串。 3.输入第一行为空格分割的多个字符串,1<单个字符串长度<100,0,1<字符串个数<100 4.输入第二行为字符规律,1<字符串个数<100 5.第二行为字符规律,1<=字符规律长度<=50 6.不需要考虑异常场景。 7.匹配的字符串在数组中的下标(从0开始),多个匹配时下标升序并用,分割,若均不匹配输出-1 8.java输出多种方法
时间: 2024-04-16 20:28:24 浏览: 153
你可以使用不同的方法来实现字符串数组与字符规律的匹配。以下是两种常见的方法:
方法一:使用正则表达式
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPatternMatcher {
public static void main(String[] args) {
String[] strings = {"abc", "def", "xyz"};
String pattern = "a,c*";
Pattern regexPattern = Pattern.compile(pattern
.replace(",", ".")
.replace("*", ".*"));
StringBuilder matchedIndices = new StringBuilder();
boolean isMatched = false;
for (int i = 0; i < strings.length; i++) {
Matcher matcher = regexPattern.matcher(strings[i]);
if (matcher.matches()) {
matchedIndices.append(i).append(",");
isMatched = true;
}
}
if (isMatched) {
matchedIndices.deleteCharAt(matchedIndices.length() - 1);
System.out.println("Matched indices: " + matchedIndices.toString());
} else {
System.out.println("-1");
}
}
}
```
方法二:使用字符串处理方法
```java
public class StringPatternMatcher {
public static void main(String[] args) {
String[] strings = {"abc", "def", "xyz"};
String pattern = "a,c*";
StringBuilder matchedIndices = new StringBuilder();
boolean isMatched = false;
for (int i = 0; i < strings.length; i++) {
if (isPatternMatch(strings[i], pattern)) {
matchedIndices.append(i).append(",");
isMatched = true;
}
}
if (isMatched) {
matchedIndices.deleteCharAt(matchedIndices.length() - 1);
System.out.println("Matched indices: " + matchedIndices.toString());
} else {
System.out.println("-1");
}
}
private static boolean isPatternMatch(String str, String pattern) {
int strIndex = 0;
int patternIndex = 0;
int strLength = str.length();
int patternLength = pattern.length();
while (strIndex < strLength && patternIndex < patternLength) {
char patternChar = pattern.charAt(patternIndex);
if (patternChar == '.') {
strIndex++;
patternIndex++;
} else if (patternChar == '*') {
char prevPatternChar = pattern.charAt(patternIndex - 1);
if (prevPatternChar == '.') {
return true; // .* 匹配任意字符串,直接返回true
} else {
while (strIndex < strLength && str.charAt(strIndex) == prevPatternChar) {
strIndex++;
}
patternIndex++;
}
} else {
if (str.charAt(strIndex) != patternChar) {
return false; // 当前字符不匹配,返回false
}
strIndex++;
patternIndex++;
}
}
return strIndex == strLength && patternIndex == patternLength;
}
}
```
以上代码示例中,我们使用了正则表达式和字符串处理方法来实现字符串数组与字符规律的匹配。其中,方法一通过正则表达式的方式进行匹配,方法二使用字符串处理方法逐个字符进行匹配。根据实际需求选择合适的方法来解决问题。
阅读全文