solution.md 1.4 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
# 最长公共前缀

<p>编写一个函数来查找字符串数组中的最长公共前缀。</p><p>如果不存在公共前缀,返回空字符串 <code>""</code></p><p> </p><p><strong>示例 1:</strong></p><pre><strong>输入:</strong>strs = ["flower","flow","flight"]<strong><br />输出:</strong>"fl"</pre><p><strong>示例 2:</strong></p><pre><strong>输入:</strong>strs = ["dog","racecar","car"]<strong><br />输出:</strong>""<strong><br />解释:</strong>输入不存在公共前缀。</pre><p> </p><p><strong>提示:</strong></p><ul>	<li><code>0 <= strs.length <= 200</code></li>	<li><code>0 <= strs[i].length <= 200</code></li>	<li><code>strs[i]</code> 仅由小写英文字母组成</li></ul>

## template

```java
class Solution {
	public String longestCommonPrefix(String[] strs) {
		if (strs.length == 0) {
			return "";
		}
		int i = 0;
		StringBuilder lcp = new StringBuilder();
		while (true) {
			boolean done = false;
			if (i >= strs[0].length()) {
				break;
			}
			for (int j = 0; j < strs.length; j++) {
				if (i < strs[j].length()) {
					if (strs[j].charAt(i) != strs[0].charAt(i)) {
						done = true;
						break;
					}
				} else {
					done = true;
					break;
				}
			}
			if (done) {
				break;
			} else {
				lcp.append(strs[0].charAt(i));
				i++;
			}
		}
		return lcp.toString();
	}
}
```

## 答案

```java

```

## 选项

### A

```java

```

### B

```java

```

### C

```java

```