0字符串简单 牛客NC.最长公共前缀 leetcode14.最长公共前缀

leetcode14.最长公共前缀

问题描述

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

思路

遍历第一条字符串的字符去和其余字符串的相同下标的字符比较。
注意遍历其余字符串时不要越界。

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

你可能感兴趣的:(字符串,leetcode)