leetcode簡單題目兩道(3)

    原本打算寫redis的,時間上有點沒顧過來,只能是又拿出點本身的存貨了。java

Problem

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:

You must do this in-place without making a copy of the array. Minimize the total number of operations.

Code:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        if (nums.size() == 0 || nums.size() == 1) {
            return;
        }
        int i = 0, j,k;
        while(i < nums.size()) {
            while (nums[i] != 0) {
                i++;
            }
            if (i < nums.size()) {
                j = i + 1;
                while (j < nums.size() && nums[j] == 0) {
                    j++;
                }
                if (j < nums.size()) {
                    k = nums[i];
                    nums[i] = nums[j];
                    nums[j] = k;
                }
                i++;
            }
        }
    }
};
說明:

用兩個下標,i保存碰到的0的位置,j表示從i以後第一個非0,交換以後i++,j繼續。
Problem:

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:

You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Code:

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern == null && str == null) {
            return true;
        }
        if (pattern == null) {
            return false;
        }
        if (str == null) {
            return false;
        }
        String[] array = str.split(" ");
        if (pattern.length() != array.length) {
            return false;
        }
        Map<String, String> map = new HashMap<String, String>();
        Set<String> value = new HashSet<String>();
        for (int i = 0; i < pattern.length(); i++) {
            String tmp = pattern.substring(i, i + 1);
            if (map.containsKey(tmp)) {
                if (array[i].compareTo(map.get(tmp)) != 0) {
                    return false;
                }
            } else {
                if (value.contains(array[i])) {
                    return false;
                }
                map.put(tmp, array[i]);
                value.add(array[i]);
            }
        }
        return true;
    }
}
說明:

發現字符串的操做仍是java的String類比較好用,此題的思路在於對待惟一,就是一個字符對應惟一的字符串,且一個串對應惟一的字符。
相關文章
相關標籤/搜索