Data Structure and algorithm-string (I)

Source: Internet
Author: User

Hey, you guys.

We haven't continued learning about the data structure for a long time. Today, let's take a look at the string, a very important data type in development. You should be familiar with strings. For example, for web development, we need to check whether the registration information entered by the user is legal, or determine whether the account, password, and information entered by the user are correct. We can solve our needs by calling string-related functions. The old saying goes with the cloud: "You know it, you know it ". What we need to do is not only call String methods, but also understand the principles of these methods. For example, before learning strings, I think to compare the two strings for equality, just like this:

            string sentence = "im a chinese";            string sentence2 = "im a brazilian";            int result = String.Compare(sentence, sentence2);            if (result > 0)                Console.Write("sentence>sentence2");            if (result == 0)                Console.Write("sentence==sentence2");            if (result < 0)                Console.Write("sentence<sentence2");

Yes. By calling the compare () method of the string class, you can determine whether sentence and sentence2 are equal. However, how does the compare () method compare two strings? Do not underestimate the string to compare this simple operation. Here we use a very powerful algorithm-The KMP pattern matching algorithm (which will be explained in detail below ). If we can master the basic algorithms for understanding these strings, it will be of great help to us in the future. That's why we need to emphasize the importance of data structures and algorithms. Programmers, who do not understand data structures or algorithms, are never qualified programmers. Now, let's learn strings together.

 

String concept:

 

The reason for the birth of a computer is that people need to use it for numerical computation. To put it bluntly, the original computer is equivalent to the calculator we usually use. The difference is that the computer is more physical than the calculator, and the computing time is faster. Slowly, computers that can only calculate numbers cannot meet the increasing needs of people. At this time, the computer began to introduce the string processing, so there was a string concept.

String: a finite sequence composed of zero or multiple characters. It is also called a string.

First, the string must be limited, that is, it must have a length. A zero-length string is called a null string ). Note that the character string with spaces is different from the empty string. See the Code:

String sentence = ""; // empty string sentence, with a length of 0 string sentence2 = ""; // string sentence2 with a space character and a length of 3

Sub-string: A sub-sequence composed of any number of consecutive characters in a string is called the sub-string of the string. Accordingly, the sub-string that contains the sub-string is called the main string.

String sentence = "beautiful"; // string subsentence = "ful"; // string

The above subsentence string can be called the Child string of the sentence string. Correspondingly, the sentence string can be called the primary string of the subsentence string.

 

String comparison

            int numberA = 12;             int numberB = 10;  // numberA>numberB            string sentenceA = "stupid";            string sentenceB = "silly";   //sentenceA>sentenceB?  sentenceA<sentenceB?   ??????

As shown in the code above, because 12 is greater than 10, numbera> numberb. Stupid and silly all mean stupid, so sentencea = sentenceb? Stupid, which is six characters, silly, which is five characters, so sentencea> sentenceb? We can compare the sizes of two numeric types. How can we compare the sizes of the two string types? When a computer processes a character, it must first encode the character. Character encoding is the subscript of a character in the corresponding character set. Therefore, the comparison between characters is also a comparison of values. Compare the subscript in the character set. Common Character sets include ASCII and Unicode.

 

ABSTRACT Data Types of strings

The element in the string data string is composed of only one character. The adjacent element has a precursor and a Successor Relationship. Operation strassign (T, * chars): generate a string t strcopy (t, s) whose value is equal to the Character String constant chars: the string s exists, copy string s to obtain string t clearstring (s): String s exists. Clear string stringempty (s): If String S is empty, true is returned, otherwise, false strlength (s) is returned. The number of elements in S is returned, that is, the string length strcompare (S, T): If S> T, the return value is greater than 0. If S <t, return value <0. If S = T, return 0 Concat (T, S1, S2): return the new string substring (sub, S, POs, len): the string s exists. 1 <= POS <= strlength (s) and 0 <= Len <= strlength (S)-pos + 1, return the index (S, T, POS) of the string with The LEN Length from the position of the POs in the S string using Sub: the string S and T exist, 1 <= POS <= strlength ( S). If there is a t string in the S string, the T string position appears for the first time after the S string POS position. If the string s does not contain a t string, 0 Replace (S, T, v) is returned: the string S, T, and V exist, and T is a non-empty string. Replace all non-overlapping strings equal to T in the primary string s with v. Strinsert (S, POs, T): String S, T exist, 1 <= POS <= strlength (s) + 1. Insert string t before the POs character of string S. Strdelete (S, POs, Len): the string s exists. 1 <= POS <= strlength (S)-len + 1. delete a string whose length is Len from string s starting from the POs character. Endadt

Are you familiar with the operations in the abstract data types of strings? Have we used these methods in our project, such as intercepting the substring () of the string and replacing the Replace () of the substring (). previously, we will only call these functions. Today we will learn how to implement these functions.

 

 

String Storage Structure

The storage structure of strings is similar to that of linear tables. They can also be sequential or chained.

Sequential storage: stores finite sequences of strings with sequential memory addresses. Assign a fixed-length storage area for each defined string variable according to the predefined size. It is generally defined by a fixed-length array.

Chain storage: Unlike linear table chain storage, if the chain storage of strings stores one character at each node like a linear table, it will cause a great waste. Therefore, the chain storage of strings, each node stores multiple characters.

 

Simple pattern matching algorithm

 

What is pattern matching? For example, you can search for a word in an English article. To put it bluntly, the string is located in the main string. Pattern matching is one of the most important operations in a string. Assume that the existing primary string S = "goodgoogle", locate the position of the substring T = "google. We need to take the following steps:

The character of the Main string matches the character of the sub-string in sequence. When the fourth position d in the main string is different from the fourth position G in the string. The second position of the primary string starts the second round of matching with the child string:

If the second-digit O of the primary string does not match the first G of the string, use the next character of O to match the substring again:

If the pairing is unsuccessful, take the next character of the last matched character in the main string and rematch it with the child string:

If the pairing is unsuccessful, continue to match the string with the main string:

The final match is successful.

Through the above steps, we can actually think of the principle of the simple pattern matching algorithm. The primary string starts from the first character and matches the characters of the Child string in sequence. The main string performs a large loop, and the Child string performs a small loop. Let's look at the algorithm:

Status Index (string S, string T, int POS) {int I = Pos; // the position where the main string starts to loop Int J = 1; // position where the string starts to loop while (I <= s [0] & J <= T [0]) // s [0] stores the length of string S, T [0] stores the string T Length {If (s [I = T [J]) {I ++; j ++ ;} else {j = 1; // when the character match is incorrect, J points to the first character I = I-j + 2 of the T string; // I points to the next character of the string s that was successfully matched last time} If (j> T [0]) return I-t [0]; else return 0 ;}

This algorithm is not hard to understand. I controls the cycle of the Main string and J controls the loop of the substring. If the pattern match is successful, the position of the T string first appears after the POs position of the primary string. If the pattern match fails, 0 is returned.

Let's analyze this algorithm. The best case is that when the first character of the Main string is matched, it will be successful and no other characters in the main string need to be matched. For example, S = "googlegood", t = "google". Slightly worse, like:

The match fails at the beginning.

In the worst case, each unsuccessful match occurs at the last digit of the substring T. For example, the primary string S = "00000000000000000000000001" substring T = "0000001". This simple pattern matching efficiency is too low. When it is low, the characters that have been judged are still being judged.

Data Structure and algorithm-string (I)

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.