当前位置:   article > 正文

leetcode-14-最长公共前缀_public class leetcode14_1 { public static void mai

public class leetcode14_1 { public static void main(string[] args) { string[

Write a function to find the longest common prefix string amongst an array of strings.

题意为编写一个函数来查找字符串数组中最长的公共前缀字符串。


这道题并不难想,首先对传入的字符串数组进行排序,然后只需要对比第一个与最后一个字符串,即可得到最长公共前缀了。


代码:

  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3. public class leetcode14 {
  4. public static void main(String[] args) {
  5. Scanner input = new Scanner(System.in);
  6. leetcode14 lt = new leetcode14();
  7. String [] strs = new String[5];
  8. for (int i = 0; i < 5; i ++){
  9. strs[i] = input.next();
  10. }
  11. System.out.println(lt.longestCommonPrefix(strs));
  12. }
  13. //AC!!
  14. public String longestCommonPrefix(String[] strs) {
  15. String ans;
  16. if (strs != null && strs.length >0) { //防止坑爹情况
  17. int num = 0;
  18. Arrays.sort(strs); // 给数组排序
  19. char[] one = strs[0].toCharArray();
  20. char[] end = strs[strs.length - 1].toCharArray();
  21. //取第一个和最后一个字符串进行比较
  22. for (int i = 0; i < one.length; i++) {
  23. if (one[i] == end[i])
  24. num++;
  25. else
  26. break;
  27. }
  28. //如果第一个字符都不相等,那就return"";
  29. if (num == 0) {
  30. return "";
  31. }
  32. //变成String类型返回
  33. char[] temp = new char[num];
  34. for (int i = 0; i < num; i++) {
  35. temp[i] = one[i];
  36. }
  37. ans = String.valueOf(temp);
  38. return ans;
  39. }
  40. return "";
  41. }
  42. }


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号