• leetcode-25-exercise_string&array


    14. Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings.

    解题思路:

    以strs[0]为标准,LCP的长度必不超过strs[0]的长度,从前向后遍历。内层遍历所有的串,如果在所有串中都有strs[0][i],

    就把它放到result中,否则返回。

    string longestCommonPrefix(vector<string>& strs) {
            int len = strs.size();
            string result = "";
            if (len == 0)
                return result;
            if (len == 1)
                return strs[0];
            if (strs[0] == "")
                return strs[0];
            for (int i = 0; i < strs[0].length(); i++) {
                for (int j = 1; j < len; j++) {
                    if (strs[j].length() == i || strs[0][i] != strs[j][i])
                        return result;
                }
                result.push_back(strs[0][i]);
            }
            return result;
        }
    

      


    219. Contains Duplicate II

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

    解题思路:

    使用unordered_map存储<nums[i], first_i>。如果当前i-first_i <= k,那就找到了。

    bool containsNearbyDuplicate(vector<int>& nums, int k) {
            if (k == 0)
                return false;
            unordered_map<int, int> m;
            for (int i = 0; i < nums.size(); i++) {
                if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)
                    return true;
                else
                    m[nums[i]] = i;
            }
            return false;
        }
    

     


     

  • 相关阅读:
    正则表达式
    JS逻辑算法
    js函数
    JS运算符的应用
    JS课堂笔记
    json模块学习
    什么是面向对象,以及如何定义对象,实例化对象
    什么是面向过程,以及代码展示
    什么是元类,以及用type类来产生类.
    python下载安装
  • 原文地址:https://www.cnblogs.com/pxy7896/p/6807913.html
Copyright © 2020-2023  润新知