zoukankan      html  css  js  c++  java
  • 字符串处理之“Known Notation”

    题目大意:介绍了一种表达式名为后缀表达式,也称为逆波兰表达式(reverse Polish notation),其运算方法是把算符放在数字之后,利用堆栈来处理计算符号的优先级以及完成计算。

    在计算时,每当检测到有  “数字 数字 算符“ 这种情况时,进行计算,将计算后的数字放在这里。

    比如:1 6 + 5 * 9 8 +  - ;第一次计算结果是  7 5 * 17 -  ;第二次是  35 17 -  ;第三次是 18 。这个算式的正常表达是  (1+6)*5-(9+8) 。

    再举几个小例子 :     1+1           转化为    1 1 +

               5+2*3        转化为    5 2 3 * +

               (5+2)*3      转化为    5 2 + 3 *

    但是此题与这种表达式并无太多关联。只需要掌握 诸如  1 1 *  合法,1 * 1不合法即可;

    给定一个字符串,只使用两种方式:

      1.插入一个数字;2.任意交换两个字符(不一定都是数字或算符);

    此题无需考虑运算优先级,只有一种运算符号 ‘*’;

    输出最小的操作次数让这个字符串成为合法的逆波兰表达式。

    样例输入               输出:

    1*1        1

    11*234**       0

    *            2

    解题思路:明显,优先处理插入,因为在字符串中,数字的个数要整好等于算符数量加一。

    应该先让两者满足这个关系,而后进行交换。

    AC代码:

     1 import java.util.*;
     2 
     3 public class Main{
     4     public static void main(String[] args){
     5         Scanner sc = new Scanner(System.in);
     6         String nn = sc.nextLine();
     7         int n = Integer.valueOf(nn);
     8         while(n > 0){
     9             String in = sc.nextLine();
    10             int num = 0;
    11             int sym = 0;
    12             int ans = 0;
    13             char[] inn = in.toCharArray();
    14             for(int i = 0;i < in.length();i ++){
    15                 if(inn[i] == '*'){sym ++;}
    16                 else{num ++;}
    17                 
    18             }
    19             int insert = sym - num + 1;
    20             if(insert > 0){ans = ans + insert;}
    21             int tn = 0;int ts = 0;
    22             for(int i = 0;i < in.length();i ++){
    23                 if(inn[i] != '*'){tn ++;}
    24                 else{
    25                     ts ++;
    26                     if(tn < ts + 1){
    27                         if(insert > 0){insert --;tn ++;}
    28                         else{tn ++;ts --;ans ++;}                        
    29                     }
    30                 }
    31                 System.out.println(tn + " " + ts);
    32             }
    33             System.out.println(ans);
    34             
    35             n --;
    36         }
    37     }
    38 }

    看不懂代码的话,自己动手模拟一下,很简单的一道题。

  • 相关阅读:
    TCP和UDP的最完整的区别
    cluster模块实现多进程-让我的代理服务速度飞起来了
    redis多实例运行
    Nodejs实现代理服务器配置
    java统计程序运行的时间
    spring boot配置写法
    Redis: OOM command not allowed when used memory > ‘maxmemory
    最新版postgresql+pgboucer安装
    spring boot 数据库连接池配置
    Spring BOOT PERFORMANCE
  • 原文地址:https://www.cnblogs.com/love-fromAtoZ/p/7245306.html
Copyright © 2011-2022 走看看