Advertisement
osipyonok

Регулярка -> обратная польская запись

Jan 4th, 2017
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.     public static void main (String[] args) throws java.lang.Exception
  11.     {
  12.         Scanner sc = new Scanner(System.in);
  13.         String s = sc.nextLine();
  14.  
  15.         Stack<Character> st = new Stack();
  16.  
  17.         String ans = "";
  18.         for(int i = 0 ; i < s.length() ; ++i){
  19.             char cur = s.charAt(i);
  20.             if(!isDelim(cur)){
  21.                 if(cur == '('){
  22.                     st.push(cur);
  23.                 }else if(isOperator(cur)){
  24.                     while(!st.empty() && getPriority(st.peek()) <= getPriority(cur)){
  25.                         ans += st.pop();
  26.                     }
  27.                     st.push(cur);
  28.                 }else if(cur == ')'){
  29.                     while(!st.empty() && st.peek() != '('){
  30.                         ans += st.pop();
  31.                     }
  32.                     if(!st.empty())st.pop();
  33.                 }else{
  34.                     ans += cur;
  35.                 }
  36.             }
  37.         }
  38.         while(!st.empty())ans += st.pop();
  39.         System.out.println(ans);
  40.     }
  41.  
  42.     static boolean isDelim(char  ch){
  43.         return ch == ' ';
  44.     }
  45.  
  46.     static boolean isOperator(char ch){
  47.         return (ch == '*' || ch == '+' || ch == '.');
  48.     }
  49.  
  50.     static int getPriority(char ch){
  51.         switch(ch){
  52.             case '*': return 1;
  53.             case '+': return 2;
  54.             case '.': return 2;
  55.             case '(': return 3;
  56.             default: return -1;
  57.         }
  58.     }
  59. }
  60. /*
  61. a.(a+b+c*)*.c*
  62. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement