LeetCode刷題——3rd

難度:簡單/Easy

序號與題目:14——最長公共前綴

編寫一個函數來查找字符串數組中的最長公共前綴。

如果不存在公共前綴,返回空字符串 ""。

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共前綴。

思考:既然是公共子串,那每個字符串肯定都包含有,並且在頭部。如果字符串數組的長度爲,則直接返回" "(這個考查字符串爲空很常見啊)。定義兩個變量i和j,用i來控制前綴長度,它的最大值爲字符串數組中元素的最小長度,這樣就要求最小字符串的長度,這個就稍顯麻煩,我們直接定義長度爲第一個字符串的長度,前綴長度肯定是小於或等於它的長度,超過前綴的部分,字符與字符肯定不同,我們可以用'\0'代替。用j來遍歷字符串數組的每個元素,當然j從1開始。當字符相同時,繼續下一個循環,不同時,置空字符

if(strs[0][i] == strs[j][i])
    continue;
strs[0][i] = '\0';

實現:

C

char* longestCommonPrefix(char** strs, int strsSize) 
{
	if(strsSize==0)	return "";
	int i,j,len = strlen(strs[0]);
	
	for(i=0;i<len;i++)
	{
		for(j=1;j<strsSize;j++)
		{
			if(strs[0][i] == strs[j][i])
				continue;
			strs[0][i] = '\0';
		}
	}
	return strs[0];
}

C++

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

Java

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        for (int i = 0; i < strs[0].length() ; i++){
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j ++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c)
                    return strs[0].substring(0, i);             
            }
        }
        return strs[0];
    }
}

Python

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return '' 
            
        max_idx = min([len(s) for s in strs])
        for i in range(max_idx, 0, -1):
            for j in range(1,len(strs)):
                if strs[j][:i] != strs[0][:i]:
                    break
            else:
                return strs[0][:i]
        return ''

序號與題目:20——有效的括號

給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。

有效字符串需滿足:

左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。

示例 1:

輸入: "()"
輸出: true
示例 2:

輸入: "()[]{}"
輸出: true
示例 3:

輸入: "(]"
輸出: false
示例 4:

輸入: "([)]"
輸出: false
示例 5:

輸入: "{[]}"
輸出: true

思考:典型的棧應用,用棧解決,複雜度O(n)。

從s中讀取字符c
    if c 是 ([{
        將 C 壓入棧
    if c 是 )]}
        if c 和彈出的字符不匹配
            出錯
讀取下一個字符 c
循環以上步驟

if 棧爲空
    匹配成功
否則出錯

實現:

C

bool isValid(char* s) 
{
    char stack[1000000];
    int top=-1;
    while(*s){
        if(*s==')'){
            if(top>=0 && stack[top]=='(')top--;
            else return false;
        }else if(*s=='}'){
            if(top>=0 && stack[top]=='{')top--;
            else return false;
        }else if(*s==']'){
            if(top>=0 && stack[top]=='[')top--;
            else return false;
        }else stack[++top]=*s;
        s++;
    }
    return top==-1;
}

C++

class Solution {
public:
    bool isValid(string s) {
        int top=-1,index=0,length=s.size();
        char* stack=(char*)malloc(sizeof(char)*length);
        while(index<length){
            if(s[index]==')'){
                if(top>=0 && stack[top]=='(')top--;
                else return false;
            }else if(s[index]=='}'){
                if(top>=0 && stack[top]=='{')top--;
                else return false;
            }else if(s[index]==']'){
                if(top>=0 && stack[top]=='[')top--;
                else return false;
            }else stack[++top]=s[index];
            index++;
        }
        return top==-1;
    }
};

Java

public class Solution {
    public boolean isValid(String s) {
        int length=s.length(),top=-1,index=0;
        char[] stack=new char[length];
        char[] str=s.toCharArray();
        while(index<length){
            if(str[index]==')'){
                if(top>=0 && stack[top]=='(')top--;
                else return false;
            }else if(str[index]=='}'){
                if(top>=0 && stack[top]=='{')top--;
                else return false;
            }else if(str[index]==']'){
                if(top>=0 && stack[top]=='[')top--;
                else return false;
            }else stack[++top]=str[index];
            index++;
        }
        return top==-1;
    }
}

Python

class Solution:
    # @param {string} s
    # @return {boolean}
    def isValid(self, s):
        length=len(s);top=-1;index=0
        stack=[' ' for i in range(length)]
        while index < length:
            if s[index]==')':
                if top>=0 and stack[top]=='(':top-=1;
                else:return False
            elif s[index]=='}':
                if top>=0 and stack[top]=='{':top-=1;
                else:return False
            elif s[index]==']':
                if top>=0 and stack[top]=='[':top-=1;
                else:return False
            else:top+=1;stack[top]=s[index]
            index+=1
        return top==-1

感謝:https://blog.csdn.net/runningtortoises/article/details/45621933

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章