Given a string which contains "G", "()","(al)". Then replace "()" with "o", "(al)" with "al" and "G" remains same
Example 1:
Input: str="G()(al)" Output: "Goal" Explanation: replace "()" with "o", replace "(al)" with "al".
Approach:
Java
public class GoalParser {
public static void main(String[] args) {
String cmd = "G()(al)";
System.out.println(goalParser(cmd));
}
public static String goalParser(String command) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < command.length(); i++) {
char c = command.charAt(i);
if (c == 'G') {
s.append(c);
} else if (c == '(' && command.charAt(i + 1) == ')') {
s.append("o");
} else if (c == 'a') {
s.append("al");
}
}
return s.toString();
}
}
C++
#include <bits/stdc++.h>
using namespace std;
string interpret(string s)
{
int n=s.size();
int i=0;
string ans="";
//iterate till the end of
//length of string
while(i<n)
{
if(s[i]=='G')
{
ans+=s[i];
i+=1;
}
//if () then ans =ans+"o"
else if(s[i]=='('&&s[i+1]==')')
{
ans+="o";
i+=2;
}
//else ans=ans+"al";
else
{
ans+="al";
i+=4;
}
}
return ans;
}
int main()
{
string str="G()(al)";
string goal=interpret(str);
cout<<goal<<"\n";
return 0;
}
No comments:
Post a Comment