计算化学式元素个数
输入任意一种物质,要求输出其每种元素的数量。
比如
输入 CaCO3,其组成分别为 Ca:1,C:1,O:3,输出 Ca1C1O3
输入 Fe2(SO4)3,其组成分别为 Fe:2,S:3,O:12,输出 Fe2S3O12
(注意:元素名称首字母大写,剩余字母都小写;括号括起来表示括号中的结构作
为整体出现多少次)
.解题思路偏向暴力解题,其次还有个bug就是一种元素重复出现会单独计算,比如OOH,会输出O1O1H1理论来说应该是输出O2H1。应该第二种输出才是对的。目前的解法实现的是第一种输出,若想实现第二种输出,在结尾时将结果集再循环一遍,重复元素的个数再次相加即可,或者直接使用map实现,同一个key的value相加。还有一个默认条件是不会出现嵌套括号,有且只有一个完整的括号出现。
public class Test {
public static void main(String args[]) {
while (true) {
Scanner read = new Scanner(System.in);
String str = read.nextLine();
int startflag = 0;
int endflag = 0;
boolean culfalg = false;
boolean isnumber = false;
boolean iskuo = false;
String result = "";
int xs = 0;
String[][] newresult = new String[100][100];
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
startflag = i;
if (i + 1 < str.length()) {
if (!Character.isLowerCase(str.charAt(i + 1)) && !Character.isDigit(str.charAt(i + 1))) {
endflag = i + 1;
culfalg = true;
}
} else {
endflag = i + 1;
culfalg = true;
}
}
if (Character.isLowerCase(str.charAt(i))) {
endflag = i + 1;
if (i + 1 < str.length()) {
if (!Character.isDigit(str.charAt(i + 1)))
culfalg = true;
}
}
if (str.charAt(i) == '(') {
iskuo = true;
}
if (str.charAt(i) == ')') {
iskuo = false;
}
if (Character.isDigit(str.charAt(i))) {
if (str.charAt(i - 1) == ')') {
xs = Integer.parseInt(str.charAt(i) + "");
continue;
}
endflag = i;
culfalg = true;
isnumber = true;
}
if (culfalg) {
if (isnumber) {
newresult[i][0] = str.substring(startflag, endflag);
newresult[i][1] = str.charAt(i) + "";
if (iskuo) {
newresult[i][2] = "true";
}
} else {
newresult[i][0] = str.substring(startflag, endflag);
newresult[i][1] = 1 + "";
if (iskuo) {
newresult[i][2] = "true";
}
}
}
culfalg = false;
isnumber = false;
}
for (int i = 0; i < 100; i++) {
if (newresult[i][2] != null && newresult[i][2].equalsIgnoreCase("true")) {
newresult[i][1] = Integer.parseInt(newresult[i][1]) * xs + "";
}
}
for (int i = 0; i < 100; i++) {
if (newresult[i][1] != null) {
result = result + newresult[i][0] + newresult[i][1];
}
}
System.out.println(result);
}
}
}