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);
    	
        }


  • 相关阅读:
    二分与三分
    NOIP应试技巧
    数论
    并差集
    最短路
    图的遍历

    最小生成树
    树状数组
    线段树
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6916219.html
Copyright © 2011-2022 走看看