淺析算法

最近閒來無事,溫習了一下算法,仍是別有風情。java

一、逆波蘭式算法

    問題描述:
express

       Evaluate the value of an arithmetic expression in Reverse Polish Notation.lua

       Valid operators are +, -, *, /. Each operand may be an integer or another expression.spa

       Some examples:code

       ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9orm

       ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6rem

    思路:字符串

        從運算表達式來看,最好用一個棧來存放這些字符串,這樣取出後,判斷運算符,從而將棧中的兩數字進行運算。get

    實現代碼:

        public int rp(String[] strs) {
		Stack<String> stack = new Stack<String>();
		String operators = "+-*/";
		for (String str : strs) {
			if (!operators.contains(str)) {
				stack.push(str);
			} else {
				Integer a = Integer.valueOf(stack.pop());
				Integer b = Integer.valueOf(stack.pop());
				int index = operators.indexOf(str);
				switch (index) {
				case 0:
					stack.push(String.valueOf(a + b));
					break;
				case 1:
					stack.push(String.valueOf(b - a));
					break;
				case 2:
					stack.push(String.valueOf(a * b));
					break;
				case 3:
					stack.push(String.valueOf(b / a));
					break;
				}
			}
		}
		return Integer.valueOf(stack.pop());
	}


二、字梯

   問題描述:

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from         start to end, such that:

        Only one letter can be changed at a time

Each intermediate word must exist in the dictionary

For example,

Given:

start = "hit"

end = "cog"

dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",

return its length 5.

Note:

Return 0 if there is no such transformation sequence.

All words have the same length.

All words contain only lowercase alphabetic characters.

    思路:

        對初給的字符串,逐字符的替換後,進行比較。

     實現代碼:

        public int getLength(String start, String end, Set<String> dict) {
		if (dict.size() == 0) {
			return 0;
		}
		LinkedList<String> wordQueue = new LinkedList<String>(); // 存放單詞
		LinkedList<Integer> distanceQueue = new LinkedList<Integer>();// 存放距離
		wordQueue.add(start);
		distanceQueue.add(1);

		while (!wordQueue.isEmpty()) {
			String currWord = wordQueue.pop();
			int distance = distanceQueue.pop();

			if (currWord.equals(end)) {
				return distance;
			}
			for (int i = 0; i < currWord.length(); i++) {
				char[] chs = currWord.toCharArray();

				// 從a~z 逐個替換 看是否符合
				for (char ch = 'a'; ch <= 'z'; ch++) {
					chs[i] = ch;
					String newWord = String.valueOf(chs);
					// 新組成的單詞是否和end相等
					if (newWord.equals(end)) {
						return distance + 1;
					}
					// 不然,接字
					if (dict.contains(newWord)) {
						wordQueue.push(newWord);
						distanceQueue.push(distance + 1);
						// 移除比較過的,不然會重複計算
						dict.remove(newWord);
					}
				}
			}
		}
		return 0;
	}


三、最長迴文串

     問題描述:

        輸入一個字符串,返回最長迴文串。好比,輸入‘adasffsff',輸出'ffsff'。

     直接上代碼:

        // 獲得最長迴文
	public String findLongestPalindrome(String str) {

		if (str.isEmpty()) {
			return null;
		}
		if (str.length() == 1) {
			return str;
		}
		int longest = 0;
		String longeststr = "";
		for (int i = 0; i < str.length(); i++) {
			String substr = getSubstr(str, i, i); // 這種獲得的是相似於這種狀況:_aba_
			if (substr.length() > longest) {
				longest = substr.length();
				longeststr = substr;
			}
			substr = getSubstr(str, i, i + 1); // 這種獲得的是相似於這種狀況:_sffs_
			if (substr.length() > longest) {
				longest = substr.length();
				longeststr = substr;
			}
		}
		return longeststr;
	}

	// 迴文子串
	public String getSubstr(String str, int start, int end) {
		while (start >= 0 && end < str.length()
				&& str.charAt(start) == str.charAt(end)) {
			// 擴大比較範圍
			start--;
			end++;
		}
		return str.substring(++start, end);
	}

   路漫漫其修遠兮,吾將上下而求索。

   待續...

相關文章
相關標籤/搜索