zoukankan      html  css  js  c++  java
  • LeetCode -- 求字符串数组中的最长公共前缀


    题目描写叙述:


    Write a function to find the longest common prefix string amongst an array of strings.
    就是给定1个字符串数组,找出公共最长前缀。




    思路非常直接。使用1个索引来存最长公共前缀的长度就能够了。


    注意, 假设使用1个字符串变量来存前缀的话,是不能AC的,由于题目不同意使用额外的空间。


    public string LongestCommonPrefix(string[] strs) {
            
        if(strs == null || strs.Length == 0){
    	    return string.Empty;
    	}
    	
    	if(strs.Length == 1){
    	    return strs[0];
    	}
    	
    	var index = 0;
    	for(var j = 0;j < strs[0].Length; j++){
    		for(var i = 1;i < strs.Length; i++){
    			if(j >= strs[i].Length || strs[0][j] != strs[i][j]){
    				return strs[0].Substring(0,index);
    			}
    		}
    		index++;
    		
    	}
    	
    	return strs[0].Substring(0 ,index);
    	
        }


  • 相关阅读:
    示波器测量电源的纹波
    hdoj 2717 Catch That Cow
    hdoj 1548 A strange lift
    hdoj 4586 Play the Dice
    zoj 2095 Divisor Summation
    hdoj 4704 Sum
    router-link传参
    字体自适应
    横向滚动div
    vue路由
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6916219.html
Copyright © 2011-2022 走看看