14. 最长公共前缀

题目:https://leetcode-cn.com/problems/longest-common-prefix/comments/

代码:

折叠复制代码
  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. int minLength = Integer.MAX_VALUE;
  4. for (String str : strs) {
  5. minLength = str.length() < minLength ? str.length() : minLength;
  6. }
  7. StringBuilder sb = new StringBuilder();
  8. for (int i = 0; i < minLength; i++) {
  9. Character c = null;
  10. for (String str : strs) {
  11. if (c == null) {
  12. c = str.charAt(i);
  13. } else if (c != str.charAt(i)) {
  14. c = null;
  15. break;
  16. }
  17. }
  18. if (c == null) {
  19. break;
  20. }else{
  21. sb.append(c);
  22. }
  23. }
  24. return sb.toString();
  25. }
  26. }

思路:
1、遍历所有字符串,一个字符一个字符进行比较,为了避免有数组越界的情况出现。所以先求出strs中所有字符串的最短的长度minLength。
2、定义索引i,从0到minLength进行逐个遍历,碰到有一个字符串在索引i的位置跟其他人不一样,就退出。


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍