Leetcode日記(2)

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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章