难度:简单/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