Number of Atoms - Leetcode 726 - Python

Поделиться
HTML-код
  • Опубликовано: 8 окт 2024

Комментарии • 109

  • @singletmat5172
    @singletmat5172 2 месяца назад +11

    I would love a 1 hr video to go over alternative solutions or going through how you think in a thorough way or certain patterns you noticed that could be applied to other problems. More information always helps :) thank you!

    • @tcdesports5673
      @tcdesports5673 2 месяца назад

      The problem with that alternative solution is, it is not that efficient. I wrote that recursive solution itself first, but was like bottom 40 %tile in both speed and memory.

  • @vishaalkumaranandan2894
    @vishaalkumaranandan2894 2 месяца назад +25

    I really loved the way you started the video

    • @mounirkanane8083
      @mounirkanane8083 2 месяца назад

      Literally only reason why I watched the whole thing

  • @yang5843
    @yang5843 2 месяца назад +32

    As a java coder, I'm joining the python bandwagon

  • @pastori2672
    @pastori2672 2 месяца назад +9

    ngl having some sort of experience with compilers made this a LOT easier to come up with and understand

    • @peakchinmayism
      @peakchinmayism 2 месяца назад +2

      Hi, can you provide some context onto what you're talking about? How did you relate this to compilers? Some examples would help.
      Just curious :)) I have that course next semester so looking forward to it.

    • @itsabdeeels
      @itsabdeeels 2 месяца назад +3

      @@peakchinmayism I think he's talking about the parsing part, doing the parsing of a compiler makes it much more easier to do the parsing of this problem.

    • @pastori2672
      @pastori2672 2 месяца назад +1

      @@peakchinmayism it is like the thing that reads your code and translates it into either machine code or assembly.. etc, in this problem we deal with string input and return the correct form so its kinda like leetcode is the programmer writing code and you're translating it to the correct form its essentially just that, i recommend you start learning C++ if you haven't already and maybe dig deeper into compilers they are a great way to reinforce your understanding of how the underlying programming language works

    • @peakchinmayism
      @peakchinmayism 2 месяца назад

      @@pastori2672 oh I got what you're trying to say. Thank you!
      I'm well versed in C++ though, don't have any experience with compilers yet. Looking forward to it.

  • @BekaMan95
    @BekaMan95 2 месяца назад +1

    Yeah Neetcode I use to be a Java dude, but as you said I've joined python church like a year ago... seems like I miss Java but I also have a good run with python so far. 🙏Thanks for all the effort you've given to series of these priceless videos.

  • @ew2430
    @ew2430 2 месяца назад +46

    Major respect to those spending their Saturday night solving this behemoth.

    • @kalmyk
      @kalmyk 2 месяца назад +2

      now try recursive solution lol

    • @leetcode571
      @leetcode571 2 месяца назад

      Being an indian, I read behemoth as "behenchod" 😂😂

    • @deltag0ny224
      @deltag0ny224 2 месяца назад

      @@kalmyk I swear the recursive solution is intuitive. Maybe it's because our university started out with recursion in the first semester.😀

  • @tusharbhatia5437
    @tusharbhatia5437 2 месяца назад +3

    Love the dedication to post daily videos !

  • @ParodyCSEDept
    @ParodyCSEDept 2 месяца назад +8

    I did using C++
    134 lines of code phew!

    • @pragadhishraajmp8871
      @pragadhishraajmp8871 2 месяца назад +2

      I got it in 44 lines
      class Solution {
      public:
      string countOfAtoms(string formula) {
      stack st;
      map m;
      int n = formula.size();
      int i = 0;
      while (i < n) {
      if (formula[i] == '(') {
      st.push(m);
      m.clear();
      i++;
      } else if (formula[i] == ')') {
      int i_start = ++i, multiplicity = 1;
      while (i < n && isdigit(formula[i])) i++;
      if (i > i_start) multiplicity = stoi(formula.substr(i_start, i - i_start));
      if (!st.empty()) {
      auto top = st.top(); st.pop();
      for (auto &p : m) top[p.first] += p.second * multiplicity;
      m = top;
      }
      } else {
      int i_start = i++;
      while (i < n && islower(formula[i])) i++;
      string name = formula.substr(i_start, i - i_start);
      int i_start2 = i, multiplicity = 1;
      while (i < n && isdigit(formula[i])) i++;
      if (i > i_start2) multiplicity = stoi(formula.substr(i_start2, i - i_start2));
      m[name] += multiplicity;
      }
      }
      string result;
      for (const auto &p : m) {
      result += p.first;
      if (p.second > 1) result += to_string(p.second);
      }
      return result;
      }
      };

  • @sum_it_
    @sum_it_ 2 месяца назад +3

    Hey nice approach. But I think if we traverse from the end of the formula it will be easier just keep a stack of the numbers and a value of the multiplied numbers till now . I'm sorry Im bad at explaining over comments

    • @justthefacts1205
      @justthefacts1205 2 месяца назад

      No, it makes sense, I seewhat tou mean it's a great idea!

  • @bundiderp5109
    @bundiderp5109 2 месяца назад +2

    Kinda proud to be able to solve this by myself, especially in Java... Even though it took over an hour.

  • @deadlyecho
    @deadlyecho 2 месяца назад +1

    Easier approach, the one I had in mind is to use a stack to track the multiplication factor whenever you step into a pair of brackets and when you step out, simply divide. The way to know the value you are going to multiply with, either pre-process the input to figure out the values and hash each bracket index to its value, or you could start backwards where you have the value before processing the inner string, I prefer the first one eaiser to code although more space but we already paying that... anyway this was much easier than the stack of hashmaps, thought of sharing it..

  • @Gomeroff
    @Gomeroff 2 месяца назад +4

    We are waiting for an hour-long analysis of the problem))

  • @shahzodshafizod
    @shahzodshafizod 2 месяца назад

    Traversing the formula backward takes O(N). Then sort the built array and collect elements joining adjacent the same ones. Sorting takes O(n log n) time

  • @daphenomenalz4100
    @daphenomenalz4100 2 месяца назад

    Knowing Go or Python is a blessing.

  • @bhagavan.unique4423
    @bhagavan.unique4423 2 месяца назад +1

    I really appreciate your hard work and dedication to solve problems for us.
    Thanks a lot Sir...🤗🤗🤗

  • @anishpandey9653
    @anishpandey9653 2 месяца назад

    Thank you so much.
    Watched this video and implemented in C++ on my own and got accepted

  • @ashwinashok1361
    @ashwinashok1361 2 месяца назад

    Very nice explanation. Thanks for simplifying the complex hard problem and making it clear and simple.

  • @akarshanjaiswal6330
    @akarshanjaiswal6330 Месяц назад

    The code will fail for "Mg(Uub)2" , we need to do slight change in solution at line 21 and 22 and change it to below
    while i+1 < len(formula) and formula[i+1].islower():
    element += formula[i+1]
    i+=1

    • @gabrielfonseca1642
      @gabrielfonseca1642 8 дней назад

      Uub is from the old periodic table, all elements have at most two characters now

  • @happybaniya
    @happybaniya 2 месяца назад

    I tried the same way but i dont manage code like you do. You have a way of simplifying thr algorithm and coding.

  • @jokerjoky3372
    @jokerjoky3372 2 месяца назад +1

    Don't u think it would easy using a recursive method which keeps iterating from the Back of the String??

  • @prainlopez2734
    @prainlopez2734 2 месяца назад

    Took about 60 lines to write in JavaScript. Here are my lessons:
    JavaScript has Regular Expressions. checking characters are even easier than Python. (as you know how to write it)
    Never use square brackets in JavaScript Map, always use get() and set().

  • @suyashgaurav448
    @suyashgaurav448 2 месяца назад +1

    Thanks

  • @JazzBrown-ym8ku
    @JazzBrown-ym8ku 2 месяца назад +3

    I had around 110 lines using C++ (brackets matching to create a stack of multipliers) admittedly there was some whitespace of course but it was a slog and it took me around an hour so not sure how this could be done in an interview setting.

    • @sojwalgosavi4406
      @sojwalgosavi4406 2 месяца назад

      65 lines

    • @JazzBrown-ym8ku
      @JazzBrown-ym8ku 2 месяца назад

      @@sojwalgosavi4406 Impressive my guy, could you maybe link your code if convenient.

  • @hemanth052
    @hemanth052 2 месяца назад +2

    how long did u take to solve it by urself ?

  • @AniruddhaErande
    @AniruddhaErande 2 месяца назад

    Great explanation and the code is very easy to comprehend

  • @abhishekkumar-fe8lw
    @abhishekkumar-fe8lw 2 месяца назад +1

    Java solution in 50 lines
    class Solution {
    public String countOfAtoms(String formula) {
    int n=formula.length();
    Stack stc=new Stack();
    Map sMap=new TreeMap();
    stc.push(sMap);
    for(int i=0;i

  • @abhijeetkumar5964
    @abhijeetkumar5964 2 месяца назад

    I don't mind if it is half hr or one hr or 2 hr video just for a single question. I would just love to grasp every bit of it.

  • @Simran_048
    @Simran_048 2 месяца назад

    Really frustrating in Cpp as well, problem seems to be lengthiest, but no simple solution found, logically not tough

  • @shubhamchouksey9904
    @shubhamchouksey9904 2 месяца назад

    Thankyou for mentioning the Java developers.

  • @lazysky1234
    @lazysky1234 2 месяца назад

    You save my weekend. Thanks my hero.

  • @LemesaElias
    @LemesaElias 2 месяца назад +1

    I thought of this approach and tried to make it work using a stack and a dictionary for about an hour, but I never knew you could store dictionaries in a stack (I know it's basic stuff). I thought it was ridiculous( I still do).

    • @gabrielfonseca1642
      @gabrielfonseca1642 8 дней назад

      if you look at the code, his stack is just a python list, and you can store anything in those. The important thing is to pop and add elements in the correct order.

  • @janardannn
    @janardannn 2 месяца назад +1

    poured a cup of tea, opened proble,, 37 mins of thinking & coding, done, tea cold

    • @niteshparihar8435
      @niteshparihar8435 2 месяца назад

      hii there , how many question have u solved on leetcode?
      i started two month ago i solved 70 question , what is roadmap please help me.

  • @devnull711
    @devnull711 2 месяца назад

    I am Java person! thank you for the video :)

  • @beinghappy9223
    @beinghappy9223 2 месяца назад

    class Solution:
    #TC:O(n^2)
    #SC:O(n)
    # Stack of hashmaps
    def countOfAtoms(self, formula: str) -> str:
    stack = [defaultdict(int)]
    i = 0
    while i < len(formula):
    if formula[i] == '(':
    stack.append(defaultdict(int))
    elif formula[i] == ')':
    curr_map = stack.pop()
    prev_map = stack[-1]
    count = ""
    cnt = 1
    while i+1

  • @manasvidobariya100
    @manasvidobariya100 2 месяца назад

    Thank you for the explanation

  • @woodylucas
    @woodylucas 2 месяца назад

    This was a really fun one

  • @vishruthpuli1664
    @vishruthpuli1664 2 месяца назад +7

    make 1hr videos and explain all the possible solutions

  • @andrewkreisher689
    @andrewkreisher689 2 месяца назад

    very cool problem,

  • @datastructure_algorithem01
    @datastructure_algorithem01 2 месяца назад

    at least I come up with good question understanding😅

  • @Vancha112
    @Vancha112 2 месяца назад

    Hmm looks like I'm skipping this one, but it seems this does get easier after really understanding what the problem actually asks.

  • @unanimous8510
    @unanimous8510 2 месяца назад

    That was really hard to code and follow even though after your explanation that solution kind of makes sense.
    I wouldn't image who could do that in a real interview in under 45 mins if that was a new problem for that person.
    Hmm, I wonder if I want to get a job at google I should solve these problems easily?
    P.S. In TS I've got 67 lines of code vs your 38 - omg!

  • @Komedy1Reels
    @Komedy1Reels 2 месяца назад

    lets convert input "Mg(OH)2" to ['Mg', '(', 'O', 'H', ')', '2'] , it will be easy to code and get the output
    class Solution:
    def preProcess(self,formula):
    fm = []
    for f in formula:
    if f.islower() or (f.isdigit() and fm[-1].isdigit()):
    fm[-1]+=f
    else:
    fm.append(f)
    return fm
    def countOfAtoms(self, formula: str) -> str:
    hm = dict()
    formula = [""]+self.preProcess(formula)[::-1]+[""]
    d = 1
    n = len(formula)
    stack = []
    for i in range(1,n):
    f = formula[i]
    pf = formula[i-1]
    if f.isdigit():
    d = d * int(f)
    elif f == ')':
    stack.append(pf)
    elif f == '(':
    x = stack.pop()
    if x.isdigit(): d = d//int(x)
    else:
    hm[f] = hm.get(f,0) + d
    if pf.isdigit():
    d = d//int(pf)
    ans = list(hm.items())
    ans.sort()
    final = ""
    for f,n in ans:
    if n == 1:
    final += f
    else:
    final += f + str(n)
    return final

  • @greatfate
    @greatfate 2 месяца назад

    traversing backwards makes this slightly simpler

  • @isltactics2093
    @isltactics2093 2 месяца назад

    it took me 2 hours to code this mammoth solution without seeing any solution

  • @AchintBhat
    @AchintBhat 2 месяца назад

    G.O.A.T!! 🙌🏻🙌🏻🙌🏻🙌🏻

  • @tunno4586
    @tunno4586 2 месяца назад

    Keep the max 30 minutes Solutions but add bonus solutions at the end.

  • @sayanbiswas2116
    @sayanbiswas2116 2 месяца назад

    this question was something a hell lot

  • @nealp9084
    @nealp9084 2 месяца назад +2

    The java solution isn't that bad! Here's a 66 line solution similar to yours.
    ```
    class Solution {
    public String countOfAtoms(String formula) {
    Stack stack = new Stack();
    stack.push(new HashMap());
    int i = 0;
    int n = formula.length();

    while (i < n) {
    if (formula.charAt(i) == '(') {
    stack.push(new HashMap());
    i++;
    continue;
    }
    if (formula.charAt(i) == ')') {
    i++;
    int count = 0;
    while (i < n && Character.isDigit(formula.charAt(i))) {
    count *= 10;
    count += (formula.charAt(i) - '0');
    i++;
    }
    count = Math.max(count, 1);
    Map map = stack.pop();
    Map prevMap = stack.peek();
    for (String s : map.keySet()) {
    prevMap.put(s, prevMap.getOrDefault(s, 0) + (map.get(s) * count));
    }
    continue;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(formula.charAt(i));
    i++;
    while (i < n && Character.isLowerCase(formula.charAt(i))) {
    sb.append(formula.charAt(i));
    i++;
    }
    int count = 0;
    while (i < n && Character.isDigit(formula.charAt(i))) {
    count *= 10;
    count += (formula.charAt(i) - '0');
    i++;
    }
    String name = sb.toString();
    count = Math.max(count, 1);
    Map map = stack.peek();
    map.put(name, map.getOrDefault(name, 0) + count);
    }
    Map map = stack.peek();
    List keys = new ArrayList(map.keySet());
    Collections.sort(keys);
    StringBuilder sb = new StringBuilder();
    for (String key : keys) {
    sb.append(key);
    int count = map.get(key);
    if (count > 1) {
    sb.append(count);
    }
    }
    return sb.toString();
    }
    }
    ```

  • @thenameisafsal
    @thenameisafsal 2 месяца назад

    1 hour? no problem let's do it!

  • @YashGupta-ty2hn
    @YashGupta-ty2hn 2 месяца назад

    A lengthy code without stack of map
    class Solution:
    def countOfAtoms(self, formula: str) -> str:
    stack = []
    i, n = 0, len(formula)
    while i < n:
    if formula[i] == ")":
    num = ""
    while i + 1 < n and formula[i + 1].isnumeric():
    num += formula[i + 1]
    i += 1
    num = int(num) if num else 1
    arr = []
    while stack[-1] != "(":
    if stack[-1].isnumeric():
    new_frequency = num * int(stack.pop())
    arr.append(str(new_frequency))
    else:
    arr.append(stack.pop())
    stack.pop()
    arr.reverse()
    stack.extend(arr)
    elif formula[i].isupper():
    element, frequency = formula[i], ""
    while i + 1 < n and formula[i + 1].islower():
    element += formula[i + 1]
    i += 1
    while i + 1 < n and formula[i + 1].isnumeric():
    frequency += formula[i + 1]
    i += 1
    stack.append(element)
    stack.append(frequency if frequency else "1")
    else:
    stack.append(formula[i])
    i += 1
    freq_map = Counter()
    for i in range(0, len(stack), 2):
    freq_map[stack[i]] += int(stack[i + 1])
    ans = ""
    for c in sorted(freq_map.keys()):
    if freq_map[c] == 1:
    ans += c
    else:
    ans += c + str(freq_map[c])
    return ans

  • @betabias
    @betabias 2 месяца назад

    I love solving problems, but today I am questioning my existence and I want to quit

  • @TenzDelek
    @TenzDelek 2 месяца назад +1

    bro is trolling java at this point

  • @maanas_sehgal
    @maanas_sehgal 2 месяца назад +1

    Java person here, neetcode should I switch to python? Where can I learn this?😊

    • @freecourseplatformenglish2829
      @freecourseplatformenglish2829 2 месяца назад

      Python is basically sudo code if you can understand the sudocode then you can code it in any language.
      Edit - Sorry I did not saw the video and commented. I guess Navdeep need to avoid build-in python functions.

    • @maanas_sehgal
      @maanas_sehgal 2 месяца назад

      @@freecourseplatformenglish2829 hmm I know how to do in java, planning to switch to python after some time

  • @yashmundada2483
    @yashmundada2483 2 месяца назад

    Isn't this incorrect.
    The problem specifically states that there will be "zero or more lowercase characters"...
    Considering only two is against the problem description

    • @NeetCodeIO
      @NeetCodeIO  2 месяца назад

      I guess the desc is wrong because I can't recall any real chemistry elements with more than two characters

  • @rajrishav
    @rajrishav 2 месяца назад

    At 28:47, do I hear the hindi word "Accha"🤔

  • @fieworjohn5697
    @fieworjohn5697 2 месяца назад

    At 19:47 N should be 2, not 1

  • @fantasticvibes6113
    @fantasticvibes6113 2 месяца назад

    no 1 hours thanks

  • @Rohan-io1yb
    @Rohan-io1yb 2 месяца назад +1

    Cpp person here lol

  • @mohanedomer9081
    @mohanedomer9081 2 месяца назад

    i was doing it in js it was 79 lines

  • @freecourseplatformenglish2829
    @freecourseplatformenglish2829 2 месяца назад +1

    Solved it on my own. To much logic is required that makes it hard otherwise it is a medium STACK Problem.

  • @limsiryuean5040
    @limsiryuean5040 2 месяца назад

    Brave person I am, get good I will

  • @saranshthukral4021
    @saranshthukral4021 2 месяца назад

    Upvote for Science👍👍

  • @eshukla15
    @eshukla15 2 месяца назад

    i love you man

  • @williamdufault6413
    @williamdufault6413 2 месяца назад

    Python solution - 28 lines:
    class Solution:
    def countOfAtoms(self, formula: str) -> str:
    atoms, element = defaultdict(int), deque()
    count, stack = deque(), ["1"]
    for character in reversed(formula):
    if character.isnumeric():
    count.appendleft(character)
    elif character == ")":
    count.appendleft("0")
    stack.append(max(1, int("".join(count))) * int(stack[-1]))
    count.clear()
    elif character == "(":
    stack.pop()
    count.clear()
    elif character.islower():
    element.appendleft(character)
    else:
    element.appendleft(character)
    count.appendleft("0")
    atoms["".join(element)] += max(1, int("".join(count))) * int(stack[-1])
    element.clear()
    count.clear()
    return "".join(
    [
    f"{element}{count}" if count > 1 else element
    for element, count in sorted(atoms.items())
    ]
    )

  • @prashanthkumar0
    @prashanthkumar0 2 месяца назад

    who's here after solving this question looking for an alternate approach

  • @Thorium-j3q
    @Thorium-j3q 2 месяца назад

    if this question comes in your interview that means they don't want to hire you

  • @raviteja3920
    @raviteja3920 2 месяца назад

    this looks like a promotional video of python 😂😂😂

  • @abhishekkrishna5978
    @abhishekkrishna5978 2 месяца назад

    Longer Video ++

  • @Logeshwar-s7m
    @Logeshwar-s7m 2 месяца назад

    implement 1 hour video

  • @zetianjin5414
    @zetianjin5414 2 месяца назад

    bro I am using Java, and I am understand most of the codes, but if there is a part I cannot understand, I will just call chatgpt to translate lol

  • @StellasAdi18
    @StellasAdi18 2 месяца назад

    Would hope such question never comes in interview.

  • @samarthtandale9121
    @samarthtandale9121 2 месяца назад

    I solved it using a queue in a bfs fashion.

  • @mikehan47
    @mikehan47 2 месяца назад +1

    Hahaha let’s translate that

  • @codenocode
    @codenocode 2 месяца назад

    I solved this in 50 lines of python code :(

  • @yang5843
    @yang5843 2 месяца назад

    Java coders watching this

  • @unstoppablecoder8110
    @unstoppablecoder8110 2 месяца назад

    First view and comment 😂

  • @parameshkumar6580
    @parameshkumar6580 2 месяца назад

    Stack of HashMaps. Seriously?

  • @qulinxao
    @qulinxao 2 месяца назад

    28:
    class Solution:
    def countOfAtoms(self, f: str) -> str:
    s,l,p=[],len(f:='('+f+')'),0
    while p

  • @Benstokes555
    @Benstokes555 2 месяца назад +2

    hello bro plz try to keep the solutions within 20 mins plz so that our concentration levels are high through out

  • @GeetainSaar
    @GeetainSaar 2 месяца назад

    Give me 1% of your property

  • @mayankpant5376
    @mayankpant5376 2 месяца назад

    wtf!! i did not solved the question yet but approach to solve this question is very simple. why the fuck this video is 33min long. what am i missing ??

  • @EduarteBDO
    @EduarteBDO 2 месяца назад

    I did this solution in rust. Before watching this, 110 lines of code and it's the O^2 solution.
    pub struct Solution;
    #[derive(Debug)]
    struct Atom {
    quantity: i32,
    symbol: String,
    }
    #[derive(Debug)]
    enum FormulaPiece {
    Atom(Atom),
    OpenParenthesis,
    CloseParenthesis(i32),
    }
    use std::collections::HashMap;
    use FormulaPiece::*;
    impl Solution {
    pub fn count_of_atoms(formula: String) -> String {
    let mut new_formula: Vec = vec![];
    let mut prev_nums: Vec = vec![];
    let mut prev_letters: Vec = vec![];
    fn insert_atom(
    new_formula: &mut Vec,
    prev_nums: &mut Vec,
    prev_letters: &mut Vec,
    ) {
    if prev_letters.len() > 0 {
    let symbol: String = prev_letters.iter().collect();
    let quantity = if prev_nums.len() == 0 {
    1
    } else {
    prev_nums.iter().fold(0, |prev, cur| prev * 10 + cur)
    };
    new_formula.push(Atom(Atom { quantity, symbol }));
    prev_letters.clear();
    prev_nums.clear();
    }
    if prev_nums.len() > 0 {
    if let Some(CloseParenthesis(_)) = new_formula.last() {
    new_formula.pop();
    new_formula.push(CloseParenthesis(
    prev_nums.iter().fold(0, |prev, cur| prev * 10 + cur),
    ));
    prev_nums.clear();
    }
    }
    }
    for c in formula.chars() {
    match c {
    '(' => {
    insert_atom(&mut new_formula, &mut prev_nums, &mut prev_letters);
    new_formula.push(OpenParenthesis);
    }
    ')' => {
    insert_atom(&mut new_formula, &mut prev_nums, &mut prev_letters);
    new_formula.push(CloseParenthesis(1));
    }
    '0'..='9' => prev_nums.push(c.to_digit(10).unwrap() as i32),
    'A'..='Z' => {
    //if it's uppercase then I know that it's a new thing.
    insert_atom(&mut new_formula, &mut prev_nums, &mut prev_letters);
    prev_letters.push(c);
    }
    'a'..='z' => prev_letters.push(c),
    _ => panic!("Should not happen"),
    }
    }
    insert_atom(&mut new_formula, &mut prev_nums, &mut prev_letters);
    let mut stack: Vec = vec![];
    for form in new_formula {
    if let CloseParenthesis(num) = form {
    let mut new_stack = vec![];
    while let Some(f) = stack.pop() {
    match f {
    OpenParenthesis => break,
    FormulaPiece::Atom(Atom { quantity, symbol }) => {
    new_stack.push(Atom(Atom {
    quantity: quantity * num,
    symbol,
    }))
    }
    _ => panic!("should not happen"),
    }
    }
    stack.extend(new_stack.into_iter());
    } else {
    stack.push(form);
    }
    }
    let mut map: HashMap = HashMap::new();
    for atm in stack {
    if let Atom(Atom { quantity, symbol }) = atm {
    *map.entry(symbol).or_insert(0) += quantity;
    }
    }
    let mut tup_elements: Vec = map.into_iter().collect();
    tup_elements.sort_unstable();
    tup_elements
    .into_iter()
    .map(|(mut key, qtd)| {
    if qtd > 1 {
    key.push_str(qtd.to_string().as_str());
    }
    key
    })
    .collect()
    }
    }

  • @vayunjain9289
    @vayunjain9289 2 месяца назад

    class Solution {
    public:
    string countOfAtoms(string s) {
    int multiplier = 1;
    stack st1;
    map mpp;
    int n = s.size();
    string t = "";
    for(int i=n-1;i>=0;i--){
    if(s[i] ='0'){
    while(s[i]='0'){
    t = s[i] + t;
    i--;
    }
    i++;
    int m = stoi(t);
    multiplier*=m;
    st1.push(m);
    }
    else if(s[i] == ')'){
    t = "";
    }
    else if(s[i] == '('){
    if(!st1.empty()){
    multiplier/=st1.top();
    st1.pop();
    }
    }
    else{
    int m = 0;
    string p = "";
    if(t == ""){
    m=1;
    }
    if(s[i]='A'){
    p+=s[i];
    }else{
    p = s[i-1];
    p+=s[i];
    i--;
    }
    mpp[p]+=multiplier;
    if(t!=""){
    if(!st1.empty()){
    multiplier/=st1.top();
    st1.pop();
    }
    }
    t="";
    }
    }
    string ans = "";
    for(auto it: mpp){
    if(it.second!=0){
    ans+=it.first;
    if(it.second > 1){
    ans+=to_string(it.second);
    }
    }
    }
    //cout