Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. #include <stack>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5.  
  6. class Decoding{
  7.  
  8. public:
  9. string decodingUtil(string str);
  10. stack<int> integerstack;
  11. stack<char> stringstack;
  12. string temp = "", result = "";
  13.  
  14.  
  15.  
  16.  
  17.  
  18. };
  19. // Returns decoded string for 'str'
  20. string decode(string str)
  21. {
  22. stack<int> integerstack;
  23. stack<char> stringstack;
  24. string temp = "", result = "";
  25. int i = 0;
  26. // Traversing the string
  27. while( i < str.length() )
  28. {
  29.  
  30. int count = 0;
  31.  
  32. // If number, convert it into number
  33. // and push it into integerstack.
  34. if (str[i] >= '0' && str[i] <='9')
  35. {
  36. while (str[i] >= '0' && str[i] <= '9')
  37. {
  38. count = count * 10 + str[i] - '0';
  39. i++;
  40. }
  41.  
  42. i--;
  43. integerstack.push(count);
  44. }
  45.  
  46. // If closing bracket ']', pop elemment until
  47. // '[' opening bracket is not found in the
  48. // character stack.
  49. else if (str[i] == ')')
  50. {
  51. temp = "";
  52. count = 0;
  53.  
  54. if (! integerstack.empty())
  55. {
  56. count = integerstack.top();
  57. integerstack.pop();
  58. }
  59.  
  60. while (! stringstack.empty() && stringstack.top()!='(' )
  61. {
  62. temp = stringstack.top() + temp;
  63. stringstack.pop();
  64. }
  65.  
  66. if (! stringstack.empty() && stringstack.top() == '(')
  67. stringstack.pop();
  68.  
  69. // Repeating the popped string 'temo' count
  70. // number of times.
  71. for (int j = 0; j < count; j++)
  72. result = result + temp;
  73.  
  74. // Push it in the character stack.
  75. for (int j = 0; j < result.length(); j++)
  76. stringstack.push(result[j]);
  77.  
  78. result = "";
  79. }
  80.  
  81. // If '[' opening bracket, push it into character stack.
  82. else if (str[i] == '(')
  83. {
  84. if (str[i-1] >= '0' && str[i-1] <= '9')
  85. stringstack.push(str[i]);
  86.  
  87. else
  88. {
  89. stringstack.push(str[i]);
  90. integerstack.push(1);
  91. }
  92. }
  93.  
  94. else
  95. stringstack.push(str[i]);
  96. i++;
  97. }
  98.  
  99. // Pop all the elmenet, make a string and return.
  100. while (! stringstack.empty())
  101. {
  102. result = stringstack.top() + result;
  103. stringstack.pop();
  104. }
  105.  
  106. return result;
  107. }
  108.  
  109. // Driven Program
  110. int main()
  111. {
  112. string str;
  113. cout << "Enter a desired string: " << endl;
  114. cin >> str;
  115. cout << decode(str) << endl;
  116. return 0;
  117. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement