- Isomorphic string
Create a hashmap where s char is the key and t char is the value. I’m going to iterate. If the map contains the key of s.kharat (I), fetch value and compare it with t.kharat (I). If the value is not equal, return false. If the map does not contain the key of s.kharat (I) but contains the value of t.kharat (I), it indicates that different characters are mapped to the same character. Return false. If the map contains neither a key for s.kharat (I) nor a value for t.kharat (I), the map is put in.
class Solution {
public boolean isIsomorphic(String s, String t) {
if (s.length() == 1) {
return true;
}
HashMap<Character, Character> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
if(map.get(s.charAt(i)) ! = t.charAt(i)) {return false; }}else {
if (map.containsValue(t.charAt(i))) {
return false;
} else{ map.put(s.charAt(i), t.charAt(i)); }}}return true; }}Copy the code
- Reverse a linked list
Head insert method
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode l = new ListNode();
ListNode t;
while(head ! =null) {
t = head.next;
head.next = l.next;
l.next = head;
head = t;
}
returnl.next; }}Copy the code
- There are duplicate elements
Check if there is a number that has already occurred. If there is a number that has already occurred, return directly
class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return false;
}
List<Integer> l = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (l.contains(nums[i])) {
return true;
} else{ l.add(nums[i]); }}return false; }}Copy the code
Official answer: Use set to determine contains more efficient, does not time out. Therefore, when a large amount of data is used to determine contains, set is highly efficient
class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums.length == 0 || nums.length == 1) {
return false;
}
Set<Integer> s = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (s.contains(nums[i])) {
return true;
} else{ s.add(nums[i]); }}return false; }}Copy the code