leetcode009--a common prefix of two strings

Source: Internet
Author: User


First, the original question



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



Second, Chinese



Write a function to find the longest public prefix in an array of strings.



Iii. Examples



str1 = "Abcmmm" str2 = "abchhhh" Its common string is ABC



Iv. train of Thought


The first step is to find the smallest length of the string, and then find the shortest most common prefix compared to its string.



v. Procedures


Package Leetcode;

public class Leetcode010 {

	private static int longprefixnum;

	public static void Main (string[] args) {
		System.out.println (longestcommonprefix ("Abcduuuu", "Abcnmwewe"));
	
	/**
	 * @param str1  string 1
	 * @param str2  string 2
	 * @return returns the longest common prefix for a string/public
	static String Longestcommonprefix (String str1, String str2) {
		if (str1 = = NULL | | str1.length () < 0 | | str2 = NULL | | str2 . Length () < 0) {return
			null;
		}
		int len1 = Str1.length ();
		int len2 = Str2.length ();
		Longprefixnum = 0;
		
		if (Len1 > Len2) {for
			(int i = 0; i < len2; i++) {
				if (Str1.charat (i) = = Str2.charat (i)) {
					longprefixnum+ +;
				} else{break;}}}
		else{for
			(int i = 0; i < len1 i++) {
				if (Str1.charat (i) = = Str2.charat (i)) {
					longprefixnum++;
				} else{break
		;
		
		}}} Return str1.substring (0, Longprefixnum);
	}



--------------------------Output--------------------------------


Abc



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.