LeetCode刷题记录(一)从简单题开始做

771 宝石与石头

https://leetcode-cn.com/problems/jewels-and-stones/

C++实现

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        char jewels[51];
        char stone[51];
        strcpy(jewels, J.c_str());
        strcpy(stone,S.c_str());
        int len = S.length();
         int num=0;
        for(int i=0;i<len;i++){
          for(int j=0;j<J.length();j++){
              if(stone[i] == jewels[j])
                    num++;
               	}
   	    	 }
        return num;
    }
};

python 实现

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        result = len([i for i in S if i in J])
        return result

1108 IP地址无效化

https://leetcode-cn.com/problems/defanging-an-ip-address/submissions/

c++实现

class Solution {
public:
    string defangIPaddr(string address) {
        int  len = address.size();
        for(int i=0;i<len;i++){
            if(address[i] == '.'){
                address.insert(i,"[");
                address.insert(i+2,"]");
                i = i+2;
                len = len+2;    
            }
        }
        return address;
    }
};

python实现

class Solution:
    def defangIPaddr(self, address: str) -> str:
        address = address.replace(".","[.]")
        return address

7 整数反转

https://leetcode-cn.com/problems/reverse-integer/

c++实现

重点在于处理越界

class Solution {
public:
    int reverse(int x) {
        long longX;
        string strX=to_string(x);
        int pos=strX.find_first_not_of("-");
        std::reverse(strX.begin()+pos,strX.end());
        stringstream out(strX);
        out >>longX;
        if(longX>INT_MAX || longX<INT_MIN)
            return 0;
        return longX;    
    }
};

python实现

class Solution:
    def reverse(self, x: int) -> int:
        flag = 1 if x >= 0 else -1
        string = str(abs(x))
        rs = string[::-1]
        x = int(rs)*flag
        if -2 ** 31 <= x <= 2**31 - 1:
            return x
        else:
            return 0

237 删除链表中的节点

https://leetcode-cn.com/problems/delete-node-in-a-linked-list/solution/

c++实现

! 直接给出的是要删除的节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

python实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

两个实现结果的内存消耗都挺大的,有待改善

发布了43 篇原创文章 · 获赞 4 · 访问量 6140

猜你喜欢

转载自blog.csdn.net/didadu/article/details/96473068
今日推荐