java - 为什么我的布尔数组不适用于 CCC 的 Problem Ragaman?
问题描述
我要解决的问题是 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
?
将与 AND 匹配的newS2.charAt(2)
is 'c' 将s1.charAt(0); charAt(1); charAt(2); and charAt(5)
布尔数组初始化为false
,因此布尔数组中的位置 0、1、2 和 5 都更新为true
while i == 2
。这不是您想要查找字谜的行为。
在找到第一个匹配项并将布尔索引设置为true
. 您的解决方案可能还有其他问题,但我认为这是主要问题。
推荐阅读
- angular - 从另一个组件调用一个角度组件
- git - 将选定的提交历史推送到 github
- powershell - 使用 Powershell 定位和更新文本文件中的键值
- javascript - 我的石头、纸、剪刀游戏的 JavaScript 代码不工作
- python - 在python中排列一个数组
- c# - 更新联结表中的数据
- javascript - Conditional set state in React
- c# - Xamarin Prism 无法导航到新页面
- python - 如何将 tar.gz 文件直接从 URL 读取到 Pandas 中?
- c# - 无法在 asp.net core 3.1 中添加对 CSharpCompilation 的 MetadataReference 的引用