题目链接:All in All,题目与串的匹配有关
import java.util.Scanner;
public class POJ1936 {
public static boolean isSubsequence (String shortStr,String lengStr)
{
char[] c1 = shortStr.toCharArray(); //子串
char[] c2 = lengStr.toCharArray(); //母串
int j = 0; //记录母串的索引
int count = 0;
//将子串的每一个字符与母串的字符比较,如果子串的字符匹配到母串中的字符后,count计数器加1,从当前母串匹配到的位置向后匹配子串的下个字符
for(int i=0;i<c1.length;i++)
{
//只要字符不匹配,将j++
while(j<c2.length && c1[i] != c2[j] )
{
j++;
}
//如果母串遍历完了,还没有匹配到,则返回false
if(j == c2.length)
{
return false;
}
if(c1[i] == c2[j])
{
count++;
j++;
}
}
//如果计数器的值等于子串的长度,则返回true
if(count == c1.length)
{
return true;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String readingStr = sc.nextLine();
while(readingStr != null)
{
String[] strArr = readingStr.split(" ");
//如果读入的子串长度大于母串的长度,直接返回No
if(strArr[0].length() > strArr[1].length())
{
System.out.println("No");
//如果两个字符串的长度相同,判断两个字符串是否相等
}else if(strArr[0].length() == strArr[1].length())
{
//如果相等,输出Yes,否则输出No
if(strArr[0].equals(strArr[1]))
{
System.out.println("Yes");
}else
{
System.out.println("No");
}
}else
{ //判断第一个字符换是否是第二个字符串的子串,如果是则输出“Yes”,否则输出“No”
boolean b =false;
b =isSubsequence(strArr[0],strArr[1]);
if(b)
{
System.out.println("Yes");
}else
{
System.out.println("No");
}
}
readingStr = sc.nextLine();
}
sc.close();
System.exit(0);
}
}
网友评论