标签:
1. Greedy Algorithm: Best Time to BUY/SELL II
package LeeCodeCrack; public class DP_BestBuySell2 { public static int bestBuySell (int[] price){ int maxProfit = 0; //If the price is not enough, then return 0 if (price==null||price.length<=1){ return 0; } //Make the lastPrice variable as the largest integer exsit, //make sure price[i] will never larger than lastPrice //before lastPrice get the value from price[i] int lastPrice=Integer.MAX_VALUE; //Record every single profit between price[i] and last price for (int i=0;i<=price.length-1;i++){ if(price[i]>lastPrice){ maxProfit+=price[i]-lastPrice; } //Given the previous value to lastprice lastPrice=price[i]; } return maxProfit; } public static void main (String[] args){ int[] array={1,2,3,4,5,6}; System.out.println(bestBuySell(array)); } }
2. (5) Stack and Queue: Simplify Path
3. Question not from Leetcode Split
This should be fairly simple, but I‘m just stuck. Say you have the path /a/b/c/
. I‘d like to convert that into an array containing:
/
/a/
/a/b/
/a/b/c/
If you need something primitive. Try split and append. public class StackOverflow { public static void main(String args[]) { String[] folders = "/a/b/c/".split("/"); String[] paths = new String[folders.length]; String path = ""; for (int i = 0; i < folders.length; i++) { path += folders[i] + "/"; paths[i] = path; } } } run: / /a/ /a/b/ /a/b/c/ BUILD SUCCESSFUL (total time: 0 seconds)
4. Stack and Queue (Simplify Path)
package LeeCodeCrack; import java.util.*; public class Stack_SimlifyPath { //解题要点,其实就是知道Java String的split function, //然后..的情况用stack,遇到..就把之间压进去的pop出来。最后stack里留下的是反过来的, //所以要用另一个stack反回来。边角case就是”//”的情况,空String不压入stack。”.”不压入stack, //遇到”..”只有stack不为空的时候才能pop,否则忽略。没有太多fancy算法。 public static String simplifyPath (String path){ String[] paths=path.split("/"); Stack<String> stack= new Stack<String>(); for (String s: paths){ if(s.equals("..")){ if(!stack.isEmpty()){ stack.pop(); } //注意length()是Method }else if (s.length()>0 && !s.equals(".")){ stack.push(s); } } //重组String StringBuilder sb =new StringBuilder(); for(String s: stack){ sb.append("/"+s); } if(sb.length()==0){ sb.append("/"); } return sb.toString(); } public static void main (String[] args){ System.out.println(simplifyPath("/a/b/../../c/")); } }
标签:
原文地址:http://www.cnblogs.com/ChrisY/p/5436029.html