Leetcode日记(2)

来源:互联网 发布:vb中picturebox画粗线 编辑:程序博客网 时间:2024/05/29 07:41

Roman to Integer

问题描述

       Given a roman numeral, convert it to an integer.
       Input is guaranteed to be within the range from 1 to 3999.

分析

       给定一个罗马数字字符串求对应的整数,罗马数字的书写方法为:相同的数字连写,所表示的数等于这些数字相加得到的数;小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数;小的数字在大的数字的左边,所表示的数等于大数减小数得到的数。因此我们逐一将字符串的罗马数字转换为整数相加 ,并记录上一次转换的值,如果出现小数在大数左边则减去两倍这个数。

解答

class Solution {public:    int romanToInt(string s) {        int Judge = GetInt(s[0]);        int result = Judge;        int Int = 0;        for (int i = 1; i < s.size(); i++)        {            Int = GetInt(s[i]);            if (Judge < Int)                result -= 2 * Judge;            result += Int;            Judge = Int;        }        return result;    }    inline int GetInt(char r)    {        switch(r)        {            case 'I': return 1;            case 'V': return 5;            case 'X': return 10;            case 'L': return 50;            case 'C': return 100;            case 'D': return 500;            case 'M': return 1000;            default: return 0;        }    }};

Longest Common Prefix

问题描述

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

分析

       依次取字符串中一个字符来比较,遇到不同时截止并返回到此位置的字符串,需要考虑输入为空的时候。

解答

class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if (strs.empty())            return "";        for (int i = 0; i < strs[0].size(); i++)        {            for (int j = 1; j < strs.size(); j++)            {                if (strs[j][i] != strs[0][i])                    return strs[0].substr(0,i);            }        }        return strs[0];    }}; 

Valid Parentheses

问题描述

       Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
       The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

分析

       根据题目,考虑可能的输入有正确的字符串,只包含一个方向的字符串,包含两个方向但不对应的字符串,用一个栈来记录从字符串中取出的左方向括号,遇到右方向括号则取出栈最上方字符对比。

解答

class Solution {public:    bool isValid(string s) {        stack<char> Judge;        for (int i = 0; i < s.size(); i++)        {            if (s[i] == '(' || s[i] == '[' || s[i] == '{')                Judge.push(s[i]);            else            {                if (Judge.empty())                    return false;                char c = Judge.top();                if (s[i] == ')' && c != '('                 || s[i] == ']' && c != '['                 || s[i] == '}' && c != '{')                    break;                Judge.pop();            }        }        if (Judge.empty())            return true;        return false;    }}; 

Merge Two Sorted Lists

问题描述

       Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

分析

       需要考虑输入为空的情况,依次比较大小进行链表的接入就可以。笔者下面的代码在本机测试无错,“||”符号会造成“短路”情况,所以笔者在if的判断语句中使用这个短路来减少代码,在过Leetcode时,会提示代码使用了空结构的数值。

解答

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if (l1 == NULL)            return l2;        if (l2 == NULL)            return l1;        ListNode result(0);        ListNode *p = &result;        for ( ; l1 != NULL || l2 != NULL; )        {            if (l2 == NULL || l1->val < l2->val) //Leetcode会报错            {                p->next = l1;                p = p->next;                l1 = l1->next;            }            else            {                p->next = l2;                p = p->next;                l2 = l2->next;            }        }        return result.next;    }};

Remove Duplicates from Sorted Array

问题描述

       Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
       Do not allocate extra space for another array, you must do this in place with constant memory.
       For example,
       Given input array nums = [1,1,2],
       Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

分析

       考虑输入为空的情况,从第二个值开始依次与前一个值比较,相同则比较下一个值,不同则长度加1,同时记录该值。

解答

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if (nums.empty())            return 0;        int result = 0;        for (int i = 1; i < nums.size(); i++)        {            if (nums[result] != nums[i])            {                result++;                nums[result] = nums[i];            }        }        return result + 1;    }};
0 0
原创粉丝点击