LeetCode (力扣) 14. Longest Common Prefix (C) - Easy

同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

题目为给定多个字符串,寻找这些字符串中,前面相同的位元。

题目与范例如下

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

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

 


解题策略为透过index ,先检查index 有没有超过第一个字符串,如果没有则依序判断有没有超过其他字符串,与是否和第一个字串相同,假设不同或超过其他字符串长度则把第一个字符串该index 设为'\0' 代表结束,最后回传第一个字符串。

下方为我的代码

char * longestCommonPrefix(char ** strs, int strsSize){

    int index = 0;                      // index control return index
    while(index<strlen(strs[0])){
        for(int i = 0;i<strsSize;i++){      // i control which str
            if(index<strlen(strs[i])){
                if(strs[0][index] == strs[i][index]){
                }
                else{
                    strs[0][index] = '\0';
                    return strs[0];
                }
            }
            else{
                strs[0][index] = '\0';
                return strs[0];
            }
        }
        index++;
    }
	return strs[0];
}

 

下方为时间与空间之消耗

Runtime: 0 ms, faster than 100 % of C online submissions for Longest Common Prefix.

Memory Usage: 5.7 MB, less than 97.7 % of C online submissions for Longest Common Prefix.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值