我试图解决的问题是 2016 年加拿大计算机比赛的高级问题 S1 (Ragaman):https ://cccgrader.com/
转述问题描述和规范:
Given two strings of length N (1 <= N <= 100), determine whether the second
string is a wildcard anagram of the first. The first string will consist
entirely of lower case letter characters, the second might also contain
asterisk characters.
我的代码(在 Java 中)已经适用于某些情况,但不是全部,而且几天来我一直试图找出我的代码的问题,但仍然找不到。我使用了不同的布尔值和 int 数组来解决这个问题。
//s1_2016
import java.util.*;
public class Main {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s1 = in.nextLine();
String s2 = in.nextLine();
String newS2 = "";
int c = 0;
//create new S2 string with no *
for(int i=0;i<s2.length();i++)
if(s2.charAt(i)!='*')
newS2 = newS2 + s2.charAt(i);
else
c++;
//makes a array of false based on the length of s1
Boolean[] boolS1 = new Boolean[101];
for(int i=0;i<101;i++)
boolS1[i]=false;
//main algorithm
for(int i=0;i<newS2.length();i++)
for(int j=0;j<s1.length();j++)
{
if((newS2.charAt(i)==s1.charAt(j))&&(boolS1[j]==false))
boolS1[j]=true;
}
//boolean found=true;
int counter = 0;
for(int i=0;i<s1.length();i++)
{
if (boolS1[i]==false)
counter++;
}
if(counter==c)
System.out.println("A");
else
System.out.println("N");
}
}
如果代码适用于两个示例问题,它很可能会起作用,但是当我尝试用更长的数字解决它时,它应该开始不起作用。提前致谢
考虑样本输入 2
cccrocks
socc*rk*
并自行完成您的“主要算法”。对于 newS2 中的每个位置,您正在测试 S1 中的每个位置以进行匹配。什么时候发生i == 2
?
newS2.charAt(2)
将与s1.charAt(0); charAt(1); charAt(2); and charAt(5)
布尔数组初始化为的AND匹配的is 'c' false
,因此布尔数组中的位置 0、1、2 和 5 都更新为true
while i == 2
。这不是您想要查找字谜的行为。
在找到第一个匹配项并将布尔索引设置为true
. 您的解决方案可能还有其他问题,但我认为这是主要问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句