最长公共前缀在Java中的字符串数组

huangapple go评论74阅读模式
英文:

Longest Common Prefix in String Array in Java

问题

public static String LongCommonPrefix(String[] strs) {
    String commonPrefix = "";
    int count = 0, k = 0;

    if (strs.length > 0) {
        for (int i = 0; i < strs[0].length(); i++) {
            int j = 1;
            while (j < strs.length) {
                if (strs[0].charAt(k) == strs[j].charAt(k)) {
                    count++;
                    j++;
                } else
                    break;
            }
            if (count == strs.length - 1) {
                commonPrefix += strs[0].charAt(k);
                count = 0;
                k++;

            } else {
                return commonPrefix;
            }
        }
    }

    return commonPrefix;
}
英文:

I am trying to find a longest common prefix in a string array using java. Following is my solution but when i upload it on leetcode, it fails and i don't understand which test case does it fail. All the test cases that I have tested works fine.

My approach is to match the first character of all the words in string array and if all words have similar first character then it move to the second character otherwise the function returns the string.

If someone helps me identify the test case where my code fails, i will be really grateful. Following is the code i have written:

public static String LongCommonPrefix(String[] strs)
	{
		String commonPrefix=&quot;&quot;;
		int count=0, k=0;
		
		if(strs.length&gt;0)
		{
			for(int i=0; i&lt;strs[0].length(); i++)
			{
				int j=1;
				while(j&lt;strs.length)
				{
					if(strs[0].charAt(k)==strs[j].charAt(k))
					{
						count++;
						j++;
					}
					else
						break;
				}
				if(count==strs.length-1)
				{
					commonPrefix+=strs[0].charAt(k);
					count=0;
					k++;

				}
				else
				{
					return commonPrefix;
				}

			}
		}

		return commonPrefix;
	}

答案1

得分: 0

你代码中的错误在于你在使用变量(K)之前没有检查该变量可能比数组的字符串长度(j)大。
为了解决这个问题,只需要在使用变量(K)之前添加一个条件语句。
祝好运。

英文:

The error in your code is in the part you used without checking that the variable (K) might be larger than the string length (j) of the array.
To solve this problem, it is enough to add a conditional statement before using the variable (K).
Good luck

答案2

得分: 0

尝试这个方法。

public static String longestCommonPrefix(String[] s) {
    if (s.length == 0) return "";

    String prefix = s[0];
    for (int i = 1; i < s.length; i++) {
        while (s[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.equals("")) return "";
        }
    }
    return prefix;
}

我已经使用以下代码进行了检查:

String[] arr = {"giorgi", "gio", "gior", "giorg", "gior"};
System.out.println(longestCommonPrefix(arr));

并且它可以很好地完成任务,输出 gio

英文:

Try this approach.

public static String longestCommonPrefix(String[] s) {
    if (s.length == 0) return &quot;&quot;;
    
    String prefix = s[0];
    for (int i = 1; i &lt; s.length; i++) {
        while (s[i].indexOf(prefix) != 0) {
            prefix = prefix.substring(0, prefix.length() - 1);
            if (prefix.equals(&quot;&quot;)) return &quot;&quot;;
        }
    }
    return prefix;
}

I have checked this with:

String[] arr = {&quot;giorgi&quot;, &quot;gio&quot;, &quot;gior&quot;, &quot;giorg&quot;, &quot;gior&quot;};
System.out.println(longestCommonPrefix(arr));

and it does the job well, by printing gio.

答案3

得分: 0

private static String findPrefix(String[] prefixes) {
    String res = "";

    if (prefixes.length == 0) return res;

    for (int i = 0; i < prefixes.length; i++) {
        char[] chars1 = prefixes[i].toCharArray();

        for (int j = i+1; j < prefixes.length; j++) {
            //break if itself
            if (i == j) continue;
            char[] charsMatch = null;
            char[] chars2 = prefixes[j].toCharArray();

            if (chars1.length > chars2.length) {
                for (int y = 0; y < chars2.length; y++) {
                    if (chars2[y] == chars1[y]) {
                        if (charsMatch == null) {
                            charsMatch = new char[chars2.length];
                        }
                        charsMatch[y] = chars1[y];
                    }
                }
            } else {
                for (int y = 0; y < chars1.length; y++) {
                    if (chars2[y] == chars1[y]) {
                        if (charsMatch == null) {
                            charsMatch = new char[chars1.length];
                        }
                        charsMatch[y] = chars1[y];
                    }
                }
            }

            if (charsMatch != null && res.length() < charsMatch.length) {
                res = new String(charsMatch);
            }
        }
    }

    return res;
}
英文:

Try this:

private static String findPrefix(String[] prefixes) {
String res = &quot;&quot;;
if (prefixes.length == 0) return res;
for (int i = 0; i &lt; prefixes.length; i++) {
char[] chars1 = prefixes[i].toCharArray();
for (int j = i+1; j &lt; prefixes.length; j++) {
//break if itself
if (i == j) continue;
char[] charsMatch = null;
char[] chars2 = prefixes[j].toCharArray();
if (chars1.length &gt; chars2.length) {
for (int y = 0; y &lt; chars2.length; y++) {
if (chars2[y] == chars1[y]) {
if (charsMatch == null) {
charsMatch = new char[chars2.length];
}
charsMatch[y] = chars1[y];
}
}
} else {
for (int y = 0; y &lt; chars1.length; y++) {
if (chars2[y] == chars1[y]) {
if (charsMatch == null) {
charsMatch = new char[chars1.length];
}
charsMatch[y] = chars1[y];
}
}
}
if (charsMatch != null &amp;&amp; res.length() &lt; charsMatch.length) {
res = new String(charsMatch);
}
}
}
return res;
}

huangapple
  • 本文由 发表于 2020年8月24日 01:43:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63550189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定