LeetCode [14/20/21] The longest common prefix, valid parentheses, merging two valid linked lists C/C++ - the second day

longest common prefix

Title Description [Simple]:
Write a function to find the longest common prefix in an array of strings.

Returns the empty string "" if no common prefix exists.

Example 1:

Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Example 2:

Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: No common prefix exists for the inputs.

Idea: (horizontal scanning method)

To traverse the strs array, first traverse the first layer through a for, and then traverse the second layer through a for, so that strs becomes a two-digit array, one word occupies one line, we only need to traverse the number of strings in the first element and it is ok Now, since we're looking for a common prefix, there's no need to search for characters longer than the length of the first element, which doesn't make sense.
When we traverse to the last column, we can stop the convenience, or when we traverse to the j-th column, the i-th row is different from the first string, so we should stop traversing again.
Finally, to return a string, you can use the substr() function.

C++

class Solution {
    
    
public:
    string longestCommonPrefix(vector<string>& strs) {
    
    
 if (strs.size() == 0) {
    
    //判断字符串是否为空
     return "";
    }
    for (int i = 0; i < strs[0].size() ; ++i) {
    
    
        char c = strs[0][i];
        for (int j = 1; j < strs.size() ; ++j) {
    
    
            if (i == strs[j].size() || strs[j][i] != c) {
    
    
                return strs[0].substr(0, i);
                }
            }
        }
        return strs[0];
    }
};

valid brackets

Brief description of the topic [simple]:
Given a string s that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

1. An opening bracket must be closed with a closing bracket of the same type.
2. Opening brackets must be closed in the correct order.

Example 1:

Input: s = "()"
Output: true

Example 2:
Input: s = "(]"
Output: false

Idea: (stack)

It is most convenient to use the stack to judge whether it appears in pairs. The idea of ​​the stack is first in, last out. When a pair of matching brackets is encountered, we delete the pair of brackets from the stack, that is, let it pop out of the stack. If the last stack is empty, then it is a valid bracket, otherwise it is not.

A hash table is used to determine whether parentheses can be formed, so as to decide whether to perform a stack operation or a stack operation.

C++

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
      unordered_map<char,int> m{
    
    {
    
    '(',1},{
    
    '[',2},{
    
    '{',3},
                                {
    
    ')',4},{
    
    ']',5},{
    
    '}',6}};
        stack<char> st;
        bool istrue = true;
        for(char c:s){
    
    
            int flag = m[c];
            if(flag >= 1 && flag<=3) 
               st.push(c);
            else if(!st.empty()&&m[st.top()]==flag-3) 
               st.pop();
            else {
    
    
                istrue=false;
                break;}
        }
        if(!st.empty()) istrue=false;
        return istrue;
    }
};
  1. First create a hash table, save three different opening brackets (对应键值分别为1,2,3)and three different closing brackets in turn (对应键值分别为4,5,6), stack (只放入开括号,若遇到对应的闭括号,则出栈), and set a bool value to judge whether it is successfully pushed into the stack (比如第一个就是闭括号,必然错误), and the default is true at the beginning.
  2. Traversing the string string through for
    1. If an opening bracket is encountered, push it onto the stack
    2. When the stack is not empty, and the corresponding closing bracket is encountered, the stack is popped
    3. Otherwise (the implicit expression at this time is 'this is a closed bracket'), the bool value is false
  3. If the stack is not empty, it means that there are fewer closing brackets, and bool is false
  4. return bool value

Merge two valid linked lists

Title Description [Easy]:
Merge two ascending linked lists into a new ascending linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists.

Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Idea: (recursive)

Recursion: As the name suggests, call yourself.
When both linked lists are empty, it means that we have merged the linked lists, and stop recursion at this time.
Recursive condition: By judging which head node of list1 or list2 is smaller, and then pointing the next pointer of the smaller node to the combined result of the remaining nodes.

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    
    
       if (list1 == NULL) {
    
    //如果list1为空,就只用输出list2
            return list2;
        }
        if (list2 == NULL) {
    
    //如果list2为空,就只用输出list1
            return list1;
        }
        if (list1->val <= list2->val) {
    
    //如果list1的头结点小于list2
            list1->next = mergeTwoLists(list1->next, list2);//list1的下一个结点指向lIst1->next和 list2 中值较小的那个结点 相当于每次拆除 list1,list2 链表首节点中值最小的那个首结点,跟前面拼接过的新链表相连,直到 list1 和 list2 当中有一个为空,就将剩余的另一个链表接到新链表后面。
            return list1;
        }
        list2->next = mergeTwoLists(list1, list2->next);
        return list2;
    }
};

Time complexity: O(m+n)

Guess you like

Origin blog.csdn.net/Lailalalala/article/details/126004370