Program to parse the Molecules and get the Atoms count
Given a chemical formula as a string, the task is to get the count of atoms in this chemical formula.
Examples:
Input: str = "Fe2H3OH"
Output: Fe 2
H 4
O 1
Input: str = "NaCl2NaO2"
Output: Na 2
Cl 2
O 2
Approach: The below approach work in Java programming language:
- Take LinkedHashMap to store atom name(Key) and count(value) in insertion order.
- Check if the string character is lowercase then add to the previous uppercase string character.
- Check if the string contains the number then add to the count(value) to their particular atom name(key).
- Print the atom name(key) as well as count(value).
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
void getCount(string str)
{
map<string, int > mp;
for ( int i = 0; i < str.length(); i++) {
int count = 0;
char c = str.at(i);
string a = " " ;
a = string(1, c);
if (a.find_first_of( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) != string::npos) {
for ( int j = i + 1; j < str.length(); j++) {
char d = str.at(j);
string b = string(1, d);
if (b.find_first_of( "abcdefghijklmnopqrstuvwxyz" ) != string::npos) {
a += b;
if (mp.find(a) == mp.end())
mp[a] = 1;
else
mp[a] += 1;
count = 1;
}
else if (b.find_first_of( "0123456789" ) != string::npos) {
int k = stoi(b);
mp[a] = k;
count = 1;
}
else {
i = j - 1;
break ;
}
}
if (count == 0) {
if (mp.find(a) == mp.end())
mp[a] = 1;
else
mp[a] += 1;
}
}
}
cout << "\nAtom count:" << endl;
for ( auto entry : mp)
cout << entry.first << " " << entry.second << endl;
mp.clear();
}
int main()
{
string str = "Fe2H3OH" ;
cout << "Given molecule: " << str << endl;
getCount(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void getCount(String str)
{
Map<String, Integer> mp
= new LinkedHashMap<String, Integer>();
for ( int i = 0 ; i < str.length(); i++) {
int count = 0 ;
char c = str.charAt(i);
String a = " " ;
a = String.valueOf(c);
if (a.matches( "[A-Z]" )) {
for ( int j = i + 1 ; j < str.length(); j++) {
char d = str.charAt(j);
String b = String.valueOf(d);
if (b.matches( "[a-z]" )) {
a += b;
if (mp.get(a) == null )
mp.put(a, 1 );
else
mp.put(a, mp.get(a) + 1 );
count = 1 ;
}
else if (b.matches( "[\\d]" )) {
int k = Integer.parseInt(b);
mp.put(a, k);
count = 1 ;
}
else {
i = j - 1 ;
break ;
}
}
if (count == 0 ) {
if (mp.get(a) == null )
mp.put(a, 1 );
else
mp.put(a, mp.get(a) + 1 );
}
}
}
System.out.println( "\nAtom count:" );
for (Map.Entry<String, Integer>
entry : mp.entrySet())
System.out.println(entry.getKey()
+ " "
+ entry.getValue());
mp.clear();
}
public static void main(String[] args)
{
String str = "Fe2H3OH" ;
System.out.println( "Given molecule: "
+ str);
getCount(str);
}
}
|
Python3
def get_count(s):
mp = {}
i = 0
while i < len (s):
count = 0
c = s[i]
if c.isupper():
a = " "
a + = c
j = i + 1
while j < len (s):
d = s[j]
if d.islower():
a + = d
if a not in mp:
mp[a] = 1
else :
mp[a] + = 1
count = 1
elif d.isdigit():
k = int (d)
mp[a] = k
count = 1
else :
i = j - 1
break
j + = 1
if count = = 0 :
if a not in mp:
mp[a] = 1
else :
mp[a] + = 1
i + = 1
print ( "\nAtom count:" )
for key, value in mp.items():
print (key, value)
mp.clear()
str = "Fe2H3OH"
print ( "Given molecule:" , str )
get_count( str )
|
C#
using System;
using System.Collections.Generic;
namespace GFG
{
class Program
{
static void getCount(String str)
{
Dictionary<String, int > mp
= new Dictionary<String, int >();
for ( int i = 0; i < str.Length; i++)
{
int count = 0;
char c = str[i];
String a = " " ;
a = c.ToString();
if (System.Text.RegularExpressions.Regex.IsMatch(a, "[A-Z]" ))
{
for ( int j = i + 1; j < str.Length; j++)
{
char d = str[j];
String b = " " ;
b = d.ToString();
if (System.Text.RegularExpressions.Regex.IsMatch(b, "[a-z]" ))
{
a += b;
if (!mp.ContainsKey(a))
mp.Add(a, 1);
else
mp[a] += 1;
count = 1;
}
else if (System.Text.RegularExpressions.Regex.IsMatch(b, "[\\d]" ))
{
int k = Convert.ToInt32(b);
mp[a] = k;
count = 1;
}
else
{
i = j - 1;
break ;
}
}
if (count == 0)
{
if (!mp.ContainsKey(a))
mp.Add(a, 1);
else
mp[a] += 1;
}
}
}
Console.WriteLine( "\nAtom count:" );
foreach (KeyValuePair<String, int > entry in mp)
Console.WriteLine(entry.Key
+ " "
+ entry.Value);
mp.Clear();
}
public static void Main(String[] args)
{
String str = "Fe2H3OH" ;
Console.WriteLine( "Given molecule: "
+ str);
getCount(str);
}
}
}
|
Javascript
function get_count(s) {
let mp = new Map();
let i = 0;
while (i < s.length) {
let count = 0;
let c = s.charAt(i);
if (c.match(/[A-Z]/)) {
let a = " " ;
a += c;
let j = i + 1;
while (j < s.length) {
let d = s.charAt(j);
if (d.match(/[a-z]/)) {
a += d;
if (!mp.has(a)) {
mp.set(a, 1);
} else {
mp.set(a, mp.get(a) + 1);
}
count = 1;
}
else if (d.match(/[0-9]/)) {
let k = parseInt(d);
mp.set(a, k);
count = 1;
} else {
i = j - 1;
break ;
}
j += 1;
}
if (count == 0) {
if (!mp.has(a)) {
mp.set(a, 1);
} else {
mp.set(a, mp.get(a) + 1);
}
}
}
i += 1;
}
console.log( "\nAtom count:" );
for (let [key, value] of mp) {
console.log(key, value);
}
mp.clear();
}
let str = "Fe2H3OH" ;
console.log( "Given molecule:" , str);
get_count(str);
|
Output:
Given molecule: Fe2H3OH
Atom count:
Fe 2
H 4
O 1
Time Complexity: O(N), Here N is the length of the string.
Auxiliary Space: O(N), The extra space is used in HashMap.
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...