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){ // Use LinkedHashmap to store // elements in insertion order map<string, int> mp; for (int i = 0; i < str.length(); i++) { int count = 0; // Convert the string element into character char c = str.at(i); string a = " "; // Convert the character element // into string element a = string(1, c); // Check string contains the Capital A - Z value. 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); // Check string contains the small a-z value. 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; } // Check string contains the number value. 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();}// Driver codeint main(){ string str = "Fe2H3OH"; cout << "Given molecule: " << str << endl; getCount(str); return 0;}// This code is contributed by surajrasr7277. |
Java
// Java program to parse the molecule// and get the atoms countimport java.io.*;import java.util.*;class GFG { static void getCount(String str) { // Use LinkedHashmap to store // elements in insertion order Map<String, Integer> mp = new LinkedHashMap<String, Integer>(); for (int i = 0; i < str.length(); i++) { int count = 0; // Convert the string element into character char c = str.charAt(i); String a = " "; // Convert the character element // into string element a = String.valueOf(c); // Check string contains the Capital A - Z value. if (a.matches("[A-Z]")) { for (int j = i + 1; j < str.length(); j++) { char d = str.charAt(j); String b = String.valueOf(d); // Check string contains the small a-z value. 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; } // Check string contains the number value. 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(); } // Driver code public static void main(String[] args) { String str = "Fe2H3OH"; System.out.println("Given molecule: " + str); getCount(str); }} |
Python3
# Python program to parse the molecule# and get the atoms countdef get_count(s): # Use dictionary to store elements in insertion order mp = {} i = 0 while i < len(s): count = 0 # Convert the string element into character c = s[i] # Check string contains the Capital A - Z value. if c.isupper(): a = " " # Convert the character element # into string element a += c j = i + 1 while j < len(s): d = s[j] # Check string contains the small a-z value. if d.islower(): a += d if a not in mp: mp[a] = 1 else: mp[a] += 1 count = 1 # Check string contains the number value. 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()# Driver codestr = "Fe2H3OH"print("Given molecule:", str)get_count(str) |
C#
using System;using System.Collections.Generic;namespace GFG{ class Program { // Method to get the count of atoms static void getCount(String str) { // Use LinkedHashmap to store // elements in insertion order Dictionary<String, int> mp = new Dictionary<String, int>(); for (int i = 0; i < str.Length; i++) { int count = 0; // Convert the string element into character char c = str[i]; String a = " "; // Convert the character element // into string element a = c.ToString(); // Check string contains the Capital A - Z value. if (System.Text.RegularExpressions.Regex.IsMatch(a, "[A-Z]")) { for (int j = i + 1; j < str.Length; j++) { char d = str[j]; String b = " "; // Convert the character element // into string element b = d.ToString(); // Check string contains the small a-z value. 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; } // Check string contains the number value. 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(); } // Driver code public static void Main(String[] args) { String str = "Fe2H3OH"; Console.WriteLine("Given molecule: " + str); getCount(str); } }}// This code added By Ajax |
Javascript
// Javascript program to parse the molecule// and get the atoms countfunction get_count(s) {// Use Map to store elements in insertion orderlet mp = new Map();let i = 0;while (i < s.length) {let count = 0;// Convert the string element into characterlet c = s.charAt(i);// Check string contains the Capital A - Z value.if (c.match(/[A-Z]/)) { let a = " "; // Convert the character element // into string element a += c; let j = i + 1; while (j < s.length) { let d = s.charAt(j); // Check string contains the small a-z value. 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; } // Check string contains the number value. 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();}// Driver codelet str = "Fe2H3OH";console.log("Given molecule:", str);get_count(str); |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
