1、reverse words
例如:输入 “ the sky is blue”
输出 “ blue is sky the”
源代码:
public String reverseWords(String s) {
if(s.equals(""))
return "";
Stack<String> stack = new Stack<String>();
StringBuilder results = new StringBuilder();
for(String str : s.split(" "))
{
if(str.equals(""))
continue;
stack.addElement(str);
}
while(!stack.empty())
results.append(stack.pop() + " ");
return results.toString().trim();
}
2、
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
即,求逆波兰式序列的值
思路:本题采用栈来存储,遍历给定字符串,如果是操作符,则取栈顶的两个数操作,并把结果压入栈,如果是数字,则将String格式转化为Int 格式的整数,其中,还要注意判断数字的符号。代码如下:
import java.util.Stack;
public class Solution2 {
public static int evalRPN(String[] tokens)
{
if(tokens.equals(""))
return 0;
Stack<Integer> stack = new Stack<Integer>();
char[] charArray = new char[tokens.length];
for(String str : tokens)
{
int operator1, operator2;
switch(str)
{
case "+" :
operator1 = stack.pop();
operator2 = stack.pop();
stack.add(operator2 + operator1);
break;
case "-":
operator1 = stack.pop();
operator2 = stack.pop();
stack.add(operator2 - operator1);
break;
case "*":
operator1 = stack.pop();
operator2 = stack.pop();
stack.add(operator2 * operator1);
break;
case "/":
operator1 = stack.pop();
operator2 = stack.pop();
stack.add(operator2 / operator1);
break;
default:stack.add(stringToInteger(str));
}
}
return stack.pop();
}
public static int stringToInteger(String s)
{
int result = 0;
int mi = 1;
Character firstChar = s.charAt(0);
for(int i = s.length() - 1; i > 0; i --)
{
int tmp = Character.getNumericValue(s.charAt(i));
result += tmp * mi;
mi *= 10;
}
if(firstChar.equals('-'))
{
return 0 - result;
}
return result + Character.getNumericValue(firstChar) * mi;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s = {"2", "1", "+" , "3", "*"};
String[] s1 = {"3", "-4", "+"};
System.out.println(evalRPN(s1));
System.out.println(stringToInteger("-4"));
}
}
3.Add Two Numbers
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int count = 0;
ListNode p1 = l1, p2 = l2, currentP = null;
l1 = null;
while(p1 != null && p2 != null)
{
int sum = p1.val + p2.val + count;
count = 0;
if(sum >= 10)
{
sum %= 10;
count = 1;
}
p1.val = sum;
if(l1 == null)
{
currentP = p1;
l1 = currentP;
}else{
currentP.next = p1;
currentP = p1;
}
p1 = p1.next;
p2 = p2.next;
}
while(p2 != null){
p2.val += count;
count = 0;
if(p2.val >= 10)
{
p2.val %= 10;
count = 1;
}
currentP.next = p2;
currentP = p2;
p2 = p2.next;
if(count == 0)
break;
}
while(p1 != null)
{
p1.val += count;
count = 0;
if(p1.val >= 10)
{
p1.val %= 10;
count = 1;
}
currentP.next = p1;
currentP = p1;
p1 = p1.next;
if(count == 0)
break;
}
if(count != 0)
{
ListNode node = new ListNode(count);
currentP.next = node;
}
return l1;
}
}
感觉每个循环里的操作都差不多,有点繁琐,有空再思考思考看看能不能合并下操作。