计算字符串中的字符数
嗨,我的代码中有一个问题,我必须计算表达式中使用的变量,当两个或多个变量相同时,应将其计算为1。例如,a+ab=使用的变量总数:2。问题是当我输入a+a=使用的变量总数:2时。 这是我的代码:
public void simplify(String strexp){
int ex =strexp.length();
for (int a=0;a<=ex-1;a++){
if(a==0)
{
if (Character.isLetter(strexp.charAt(a)))
{
b++;
}
}
else{
for(int c=0;c<=a-1;c++){
if (Character.isLetter(strexp.charAt(c))==Character.isLetter(strexp.charAt(a)))
{
System.out.println("equal");
break;
}
else if (Character.isLetter(strexp.charAt(c))!=Character.isLetter(strexp.charAt(a)))
{
//if(c==a-1)
//{
b++;
System.out.println("nomatch");
// }
}
}
}
}
JOptionPane.showMessageDialog(null, b);
}
# 1 楼答案
使用列表来计算变量的总量
这是打印出来的
# 2 楼答案
你需要跟踪你看到的变量。一种方法可能是使用
Set<char>
。每当你看到一个角色,就把它添加到集合中。唯一运算符的数量将是集合中的字符数