力扣题-10.25
力扣题1:205. 同构字符串
解题思想:同昨天的题目,维护两个字符串的映射关系即可
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
ch12ch2 = dict()
ch22ch1 = dict()
if len(s) != len(t):
return False
for ch1,ch2 in zip(s,t):
if (ch1 in ch12ch2 and ch12ch2[ch1]!=ch2) or (ch2 in ch22ch1 and ch22ch1[ch2]!=ch1):
return False
ch12ch2[ch1]=ch2
ch22ch1[ch2]=ch1
return True
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> ch12ch2;
unordered_map<char, char> ch22ch1;
int len = t.length();
for(int i =0;i<len;++i){
char ch1 = s[i],ch2 = t[i];
if((ch12ch2.count(ch1) && ch12ch2[ch1] != ch2)||(ch22ch1.count(ch2) && ch22ch1[ch2] != ch1)){
return false;
}
ch12ch2[ch1]=ch2;
ch22ch1[ch2]=ch1;
}
return true;
}
};
力扣题2:138. 复制带随机指针的链表
解题思想:第一遍遍历先创建与原先节点相对应的节点链表,第二遍遍历填写random指针的地址
"""
# Definition for a Node.
class Node:
def __init__(self, x, next=None, random=None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
temp = head
node_list = dict()
new_head = Node(0,None,None)
pre_node = new_head
while temp!=None:
new_node = Node(temp.val,None,None)
pre_node.next = new_node
pre_node = pre_node.next
node_list[temp]=new_node
temp = temp.next
temp = head
temp2 = new_head.next
while temp!=None:
if temp.random!=None:
temp2.random = node_list[temp.random]
temp = temp.next
temp2 = temp2.next
return new_head.next
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* temp = head;
unordered_map<Node*, Node*> node_list;
Node* new_head = new Node(0);
Node* pre_node = new_head;
while(temp!=NULL){
Node* new_node = new Node(temp->val,NULL,NULL);
pre_node->next = new_node;
pre_node = pre_node->next;
node_list[temp] = new_node;
temp = temp->next;
}
temp = head;
Node* temp2 = new_head->next;
while(temp!=NULL){
if(temp->random!=NULL){
temp2->random = node_list[temp->random];
}
temp = temp->next;
temp2 = temp2->next;
}
return new_head->next;
}
};