Caching popular contents at mobile devices can potentially improve the quality of service for mobile users and relieve traffic burden of base station in cellular networks. In this paper, we jointly consider the resource allocation, the cached contents, and the distance between two devices for the optimal device pairing problem in centralized and distributed cases, where the BS is the central controller in the centralized case. The joint optimization problem of device-to-device (D2D) caching with channel allocation is formulated as a weighted four-uniform hypergraph model. The optimal solution for the problem is 4-D maximum weighted matching (4-DMWM), which is NP-hard unfortunately. To approach the 4-DMWM with low-complexity, we adopt the greedy algorithm and the squareIMP algorithm in the centralized case. Moreover, distributed algorithms are also designed for the caching problem in both synchronous and asynchronous cases. The simulation results will illustrate that the squareIMP algorithm can be used to get a better transmission rate with the complexity of O(n(5)), while the greedy algorithm can be used in the case with stringent latency requirement for centralized 4-DMWM problem. The sum rate of distributed asynchronous algorithm is close to the centralized greedy algorithm with the complexity of O(n(2)) for each device. However, the simulation result of the synchronous algorithm is slightly lower than the centralized algorithm, where each device performs O(n(2)) computational operations in each iteration. Therefore, the algorithms proposed in this paper can be used in different cases for solving optimal D2D pairing and channel allocation problem.