TVP

算法之求String类型算数表达式的值 和 验证IP地址合法性

CoffeeLand

6410

验证IP地址合法性

``````import org.apache.commons.validator.routines.InetAddressValidator;

public class IPValidator
{
public static Boolean checkIpValid(String str)
{
return false;
}

public static void main(String[] args)
{
final String ipv4 = "10.8.9.28";

final String ipv6 =
"2001:0db8:85a3:0000:0000:8a2e:0370:7334";
Boolean res4 = checkIpValid(ipv4);
System.out.println("res4 = " + res4);
Boolean res6 = checkIpValid(ipv6);
System.out.println("res6 = " + res6);

}
}
``````

String类型算数表达式的值

``````import java.util.Stack;

class Calculator {

final static Stack<Character> opStack = new Stack<>();

/**
* calculate the value of the suffix expression
* @param expr - the input string expression
* @return - result of the expression
*/
public static int calc(String expr){
// transfer the string format from infix to suffix
String suffix = transferToSuffix(expr);
Stack<Integer> resStack = new Stack<>();
char[] arr = suffix.toCharArray();
for(char ch : arr)
{
if (Character.isDigit(ch)) resStack.push(Integer.valueOf(ch - '0'));
else resStack.push(calResWithOperation(ch, resStack.pop(), resStack.pop()));
}
return resStack.pop();
}

/**
* transfer the string format from infix to suffix
* @param expr - String in the form of infix
* @return String in the form of suffix
*/
private static String transferToSuffix(String expr){
char[] arr = expr.replaceAll(" ","").toCharArray();
int len = arr.length;
String suffix = "";

for(int i = 0; i < len; i++)
{
char ch = arr[i];
// output if the char is number
if(Character.isDigit(ch))
{
suffix+=ch;
continue;
}

// push to the stack directly if char is '('
if(ch == '(') {
opStack.push(ch);
continue;
}

if(ch == '+' || ch == '-'){
while(!opStack.empty() && (opStack.peek() != '('))
suffix+= opStack.pop();
opStack.push(ch);
continue;
}

if(ch == '*' || ch == '/'){
while(!opStack.empty() && (opStack.peek() == '*' || opStack.peek() == '/'))
suffix+= opStack.pop();
opStack.push(ch);
continue;
}

// pop the stack
if(ch == ')'){
while(!opStack.empty() && opStack.peek() != '(')
suffix += opStack.pop();
opStack.pop();
continue;
}
}

while(!opStack.empty()) suffix += opStack.pop();
return suffix;
}

/**
* calculate the two numbers with operation
*
* @param op the operation symbol
* @param num1 the calculated number
* @param num2 the calculated number
* @return the calculate result
*/
private static int calResWithOperation(char op, int num1, int num2){
if (op == '+') return num2 + num1;
else if (op == '-') return num2 - num1;
else if (op == '*') return num2 * num1;
else if (op == '/') return num2 / num1;
else return 0;
}

public static void main(String[] args){
String exp = "1+2* (3+4)";
String postfix = transferToSuffix(exp);
System.out.println("postfix = " + postfix); // postfix = 1234+*+
int res = calc(postfix);
System.out.println("res = " + res);  // res = 15
}
}``````

0 条评论

LV.

• 验证IP地址合法性
• String类型算数表达式的值