Tag Archives: 编码

LeetCode Game of Life

289. Game of Life 289. Game of Life

According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? 289. Game of Life

本题有关康威生命游戏,第一次听说。。。 给一个二维矩阵,0表示死亡,1表示活着。每个细胞根据周围8个细胞的状态,有如下跳转规则:

  1. 活着的细胞周围有少于2个活着的细胞,则该细胞死亡
  2. 活着的细胞周围有2个或3个活着的细胞,则该细胞继续活着
  3. 活着的细胞周围有多于3个活着的细胞,则该细胞死亡
  4. 死亡的细胞周围有3个活着的细胞,则该细胞复活

最简单的方法是复制一个矩阵,遍历原矩阵然后更新新矩阵。但本题的难点是,要在in-place的情况下更新原矩阵。如果还是像之前那样更新的话,当前细胞的状态更新之后,会影响到后续细胞的判断,不可行。 参考网上题解,使用编码方法。 因为输入是以int来存储细胞状态的,int可以存储的状态数就很多了,不仅仅局限于0和1。 假设细胞状态重新编码如下:

  • 0:0→0,原来死亡,现在还死亡
  • 1:1→1,原来活着,现在还活着
  • 2:1→0,原来活着,现在死亡
  • 3:0→1,原来死亡,现在活着

则还是像之前一样,遍历细胞的周围8个点,根据以上编码可以知道周围细胞更新前的状态,比如某个邻居的状态是2,则知道该邻居更新前是1活着的。 所有细胞都更新完之后,需要复原成0,1编码,则状态为0和2表示新状态是死亡0,状态是1和3表示新状态是活着1。这可以用新状态对2取余数得到。 代码如下:

class Solution {
public:
    void gameOfLife(vector<vector<int> >& board)
    {
        int m = board.size(), n = 0;
        if (m != 0)
            n = board[0].size();
        if (m == 0 || n == 0)
            return;
        vector<vector<int> > dirs = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } };
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int lives = 0;
                for (int k = 0; k < dirs.size(); ++k) {
                    int x = i + dirs[k][0], y = j + dirs[k][1];
                    if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2))
                        ++lives;
                }
                if (board[i][j] == 1 || board[i][j] == 2) {
                    if (lives < 2 || lives > 3)
                        board[i][j] = 2;
                    else
                        board[i][j] = 1;
                }
                else if (lives == 3)
                    board[i][j] = 3;
            }
        }
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                board[i][j] %= 2;
            }
        }
    }
};

本代码提交AC,用时3MS。

二刷。 很简单,也不用定什么规则,直接按位编码,第0位是原来的状态,0为死1为生,第1位是更新后的状态,依然是0为死1为生,所有状态更新完之后,右移一位即可。代码如下:

class Solution {
public:
	void gameOfLife(vector<vector<int>>& board) {
		int m = board.size(), n = board[0].size();

		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {

				int lives = 0;
				int u = max(0, i - 1), v = max(0, j - 1);
				int x = min(m, i - 1 + 3), y = min(n, j - 1 + 3);
				for (int a = u; a < x; ++a) {
					for (int b = v; b < y; ++b) {
						if (a == i && b == j)continue;
						if ((board[a][b] & 1) == 1)++lives;
					}
				}

				int curlive = (board[i][j] & 1);
				if (curlive == 1 && lives < 2) {
					board[i][j] = (board[i][j] | (0 << 1));
				}
				else if (curlive == 1 && (lives == 2 || lives == 3)) {
					board[i][j] = (board[i][j] | (1 << 1));
				}
				else if (curlive == 1 && (lives > 3)) {
					board[i][j] = (board[i][j] | (0 << 1));
				}
				else if (curlive == 0 && lives == 3) {
					board[i][j] = (board[i][j] | (1 << 1));
				}

			}
		}

		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				board[i][j] >>= 1;
			}
		}

	}
};

本代码提交AC,用时0MS。

LeetCode Longest Substring with At Least K Repeating Characters

LeetCode Longest Substring with At Least K Repeating Characters Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. Example 1:

Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

给定一个字符串s和数字k,求s的子串中每个字母都至少出现k次的最长子串的长度。 因为题目规定字符串中只有26个小写字母,所以可以用一个int来Hash某个子串,如果某字母出现次数小于k次,则对应位为1,否则对应位为0。最后,在遍历的过程中,判断子串的Hash值是否等于0,如果是则该子串满足要求,更新最大长度。 完整代码如下: [cpp] class Solution { public: int longestSubstring(string s, int k) { int maxLen = 0; for (int i = 0; i < s.size(); ++i) { vector<int> mask(26, 0); int j = i, flag = 0; while (j < s.size()) { ++mask[s[j] – ‘a’]; if (mask[s[j] – ‘a’] < k)flag |= (1 << (s[j] – ‘a’)); else flag &= (~(1 << (s[j] – ‘a’))); if (flag == 0)maxLen = max(maxLen, j – i + 1); ++j; } } return maxLen; } }; [/cpp] 本代码提交AC,用时196MS。]]>

LeetCode Maximum Product of Word Lengths

LeetCode Maximum Product of Word Lengths Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. Example 1: Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] Return 16 The two words can be "abcw", "xtfn". Example 2: Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] Return 4 The two words can be "ab", "cd". Example 3: Given ["a", "aa", "aaa", "aaaa"] Return 0 No such pair of words.


给定一个字符串数组,问两个没有共同字母的字符串的长度之积最大是多少,如果不存在这样两个字符串,则返回0。 常规思路是两层循环,判断两个字符串是否有共同字符,没有就把它俩的长度乘起来,更新最大值。 问题的关键就是如果快速的判断两个字符串是否有共同字符,常规思路是把一个字符串Hash,然后对另一个字符串的每个字符,看是否在前一个字符串中出现。快速方法是,因为题目说明字符串中只有小写字母,也就是只有26种情况,所以我们可以对这26个字母编码成一个26长的bit位,用一个int存储足够。这样判断两个字符串是否有共同字符,只需要把两个int相与,等于0表示没有共同字符。 完整代码如下: [cpp] class Solution { public: int maxProduct(vector<string>& words) { int ans = 0; vector<int> mask(words.size(), 0); for (int i = 0; i < words.size(); ++i) { for (int j = 0; j < words[i].size(); ++j) { mask[i] |= 1 << (words[i][j] – ‘a’); } for (int k = 0; k < i; ++k) { if ((mask[i] & mask[k]) == 0) // 注意 == 的优先级高于 & ans = max(ans, int(words[i].size()*words[k].size())); } } return ans; } }; [/cpp] 本代码提交AC,用时69MS。]]>