# 205. Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

Note:

You may assume both s and t have the same length.

/*solution1,use two unordered_map,24ms*/
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size()!=t.size())
return false;
unordered_map<char,char> hash;
int i=0;
for(i=0;i<s.size();i++){
if(hash.find(s[i])!=hash.end()){
if(hash[s[i]]!=t[i])
return false;
}
else{
for(unordered_map<char,char>::iterator it=hash.begin();it!=hash.end();it++){
if(it->second==t[i])
return false;
}
hash[s[i]]=t[i];
}
}
return i==s.size();
}
};


/*solution2,use two arrays,8ms*/
class Solution {
public:
bool isIsomorphic(string s, string t) {
int map1[256]={0},map2[256]={0},i=0;/*数组要初始化为0*/
for(i=0;i<s.size();i++){
if(map1[s[i]]!=map2[t[i]])/*如果s中的字符映射之后和t中字符映射之后不相等，则返回false;
首次进入循环时，两个字符映射之后的值都为0，所以不会返回false*/
return false;
map1[s[i]]=map2[t[i]]=i+1;/*否则将其更新为同一个值*/
}
return i==s.size();
}
};


# 你为什么招不到人？那些搞通信的都去哪了？

“X总，我… 我要离职。”

“你讲的道理我都懂，但是，没用的，我必须走，没有办法，我也不想。”

# 290. Word Pattern

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.

class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char,string> hash;
istringstream in(str);/*构造字符串流时，空格会成为其内部分界，这也是拆分含有空格的字符串的方法之一*/
int i=0;
for(string word;in>>word;i++){
if(hash.find(pattern[i])!=hash.end()){
if(hash[pattern[i]]!=word)
return false;
}
else{
for(unordered_map<char,string>::iterator it=hash.begin();it!=hash.end();it++){
if(it->second==word)
return false;
}
hash[pattern[i]]=word;
}
}
return i==pattern.size();
}
};


# 299. Bulls and Cows

You are playing the following Bulls and Cows game with your friend:

You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

Secret number:  "1807"
Friend's guess: "7810"


Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return “1A3B”.

Please note that both secret number and friend’s guess may contain duplicate digits, for example:

Secret number:  "1123"
Friend's guess: "0111"


In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return “1A1B”.

You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

Using array as a simple counter

A simple array could be used as a counter. An array could be used to keep track of the frequency of each character. For example, if the input consists of ASCII characters, we could just use an integer array of size 256 to keep track of the frequency.

For example, the following program calculates each character’s frequency using a simple array of size 256.

private static void printFreq(char[] str) {
int[] freq = new int[256];
for (int i = 0; i < str.length; i++) {
freq[str[i]]++;
}
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
System.out.println("[" + (char)(i) + "] = " + freq[i]);
}
}
}

public static void main(String[] args) {
char[] str = "Hello world".toCharArray();
printFreq(str);
}


Output:

[ ] = 1
[H] = 1
[d] = 1
[e] = 1
[l] = 3
[o] = 2
[r] = 1
[w] = 1


Why do we choose size 256? Why not 128 or 26? The reason is because there are a total of 256 possible ASCII characters, from 0 to 255. If you are sure that the input characters are all lowercase letters (a - z), then you can save some space by using an array of size 26:

private static void printFreq(char[] str) {
int[] freq = new int[26];
for (int i = 0; i < str.length; i++) {
// 'a' has an ascii value of 97, so there is an offset in accessing the index.
freq[str[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
System.out.println("[" + (char)(i + 'a') + "] = " + freq[i]);
}
}
}

public static void main(String[] args) {
char[] str = "helloworld".toCharArray();
printFreq(str);
}


Output:

[d] = 1
[e] = 1
[h] = 1
[l] = 3
[o] = 2
[r] = 1
[w] = 1


Using a hash table

Now, what if the input contains unicode characters? In Java, each character is represented internally as 2 bytes, or 16 bits. That means you can increase the array size to 2^{16} = 65536 2^16=65536, which would work but seems like a waste of space. For example, what if your input has only 10 characters? Most of the array elements will be initialized to 0 and to print the frequencies we need to traverse all 65536 elements one by one, which is inefficient.

A better method is to use a hash table, in Java it’s called HashMap, in C++ it’s called unordered_map, and in Python it’s called dict.

private static void printFreq(char[] str) {
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < str.length; i++) {
if (freq.containsKey(str[i])) {
freq.put(str[i], freq.get(str[i]) + 1);
} else {
freq.put(str[i], 1);
}
}
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println("[" + (char)(entry.getKey()) + "] = " + entry.getValue());
}
}

public static void main(String[] args) {
char[] str = "◣⚽◢⚡◣⚾⚡◢".toCharArray();
printFreq(str);
}


Output:

[⚡] = 2
[◢] = 2
[◣] = 2
[⚽] = 1
[⚾] = 1


class Solution {
public:
string getHint(string secret, string guess) {
if(secret.empty()||guess.empty())
return "0A0B";
vector<int> countS(10,0);
vector<int> countG(10,0);
string res;
int countA=0,countB=0;
for(int i=0;i<secret.size();i++){
if(secret[i]==guess[i])
countA++;
else{
/*统计不成对元素个数*/
countS[secret[i]-'0']++;
countG[guess[i]-'0']++;
}
}
for(int i=0;i<countS.size();i++)
countB+=min(countS[i],countG[i]);
res=to_string(countA)+'A'+to_string(countB)+'B';
return res;
}
};




# 你连世界都没有观过，哪里来的世界观？

“为什么我比你有才还没你混得好？”

“因为我见得比你多啊”

-01-

-02-

“利用碎片时间，等人的时间、坐车的时间、走路的时间（用语音记录）、做菜的时间（听课程音频），实在不行就早起一小时，时间挤挤总会有的。”

-03-

-END-