Leetcode string A

Source: Internet
Author: User
Tags map data structure strlen alphanumeric characters

1. Length of Last Word

Given A string s consists of Upper/lower-case alphabets and empty space characters ' ", return the length of last word in The string.

If The last word does isn't exist, return 0.

Note:a word is defined as A character sequence consists to non-space only.

For example,
Given s = "Hello World",
Return 5. This is a realization problem, from the forward scan, how to judge the last word, there are several situations

1. "Word"

2. ""

3. "Word"

4. "Word"

int Lengthoflastword (const char *s) {
    int length = strlen (s);
    int count = 0;
    for (int i= length-1; i>=0;i--) {
        if (s[i] = = ') {
            if (count = = 0) continue;
            else return count;
        count++;
    }
    return count;
}

Java Solution:

Use the split () function to group the original string with the space ""

public int Lengthoflastword (string s) {
        string [] splitstrings = S.split ("");
        	for (int i=splitstrings.length-1;i>=0;i--) {
        		if (splitstrings[i].length () >0) return
        			Splitstrings[i] . Length ();
        	}
        	return 0;
    }



2. Longest Common Prefix

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

string search, implementation problem.

Defines a compare string that holds the final result, iterates through the array, and finds the corresponding prefix each time it is saved to the compare

String Longestcommonprefix (vector<string> &strs) {
    if (strs.size () = = 0) return NULL;
    string compare = Strs[0];
    for (int i=1; i<strs.size (); i++) {
        string prefix;
        int k=0;
        while (K<compare.size () && k<strs[i].size ()) {
            if (compare[k)!= strs[i][k]) break;

            Prefix.append (1,compare[k]);
            k++;
        }
        Compare.clear ();
        Compare.append (Prefix.c_str ());
    }
    return compare;
}

Solution Two

Scan from the ' the ' character, if it is same to all strings, then scan the second one until meet or null

Java implementation

Public String Longestcommonprefix (string[] strs) {
        if (strs.length = = 0) return "";
        Boolean flag = true;
		for (int i=0;i<strs[0].length (), i++) {for
			(int j=0;j<strs.length;j++) {
				if (i>=strs[j].length () | | Strs[0].charat (i)!=strs[j].charat (i)) {
					flag = false;
					break;
				}
			}
			if (!flag) return strs[0].substring (0,i);
		}
		return strs[0];
    }



3.Count and Say

The Count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
One is read off as "two 1s" or 21.
The is read off as "One 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note:the sequence of integers would be represented as a string.

String operations, N-time loops construct the nth string, and the construction process passes the characters preceding the number. Note here use I<=result.size () to omit the judgment to reach the end of the string

string Countandsay (int n) {
    string result = ' 1 ';
    int level = 1;
    while (Level < n) {
        stringstream seq;
        Char last = result[0];
        int count =0;
        for (int i=0; i<=result.size (); i++) {
            if (result[i] = last) {
                count++;
                Continue;
            }
            else{
                seq<<count<<last;
                Count = 1;
                last = Result[i];
            }
        result = Seq.str ();
        level++;
    }
    return result;
}

Java

public string Countandsay (int n) {
        String result = ' 1 ';
        if (n==1) return result;
        int level = 1;
        while (level<n) {
        	char last = result.charat (0);
        	int count =0;
        	StringBuffer seq = new StringBuffer ();
        	for (int i=0;i<result.length (); i++) {
        		if (last = = Result.charat (i)) {
        			count++;
        			Continue;
        		} else {
					seq.append (count);
					Seq.append (last);
					last = Result.charat (i);
					Count=1
				}
        	}
        	Seq.append (count);
			Seq.append (last);
        	result = Seq.tostring ();
        	level++;
        }
        return result;
    }


4.

Implement Strstr ().

Returns a pointer to the ' the ' of needle in haystack, or null if needle was not part of haystack. The solution of time complexity linear is obviously KMP algorithm

1. The ordinary solution.

2. Introduction to the KMP algorithm---algorithm chapter 32

Char *strstr (char *haystack, char *needle) {
    if (haystack = = NULL | | needle = NULL) return null;
    int hlength = strlen (haystack);
    int nlength = strlen (needle);
    if (hlength<nlength) return NULL;
    for (int i=0; i

Method 2

public string Strstr (String haystack, string needle) {
		if (haystack.length () <=0 && needle.length () >0) return null;
        for (int i=0;i<=haystack.length ()-needle.length (); i++) {
        	Boolean flag = true;
        	for (int j=0;j<needle.length (); j + +) {
        		if (Haystack.charat (I+j)!=needle.charat (j)) {
        			flag = false;
        			break;
        		}
        	}
        	if (flag) {return
    			haystack.substring (i);
    		}
        }
        return null;
    }


Method 3

Reference

http://blog.csdn.net/lin_bei/article/details/1252686

Introduction to Algorithms, Chapter 32


5. Valid palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring.

For example,
"A man, a plan, a Canal:panama" is a palindrome.
' Race a car ' is not a palindrome.

Note:
Have you consider the string might to be empty? This is a good question to ask during a interview.

For the purpose of this problem, we define empty string as valid palindrome. Analysis:

Use two pointers and scan from the end to start.

Java

public Boolean ispalindrome (String s) {
        s = S.trim ();
		if (S.length () <=0) return true;
		int start = 0;
		int end = S.length ()-1;
		while (Start<end) {while
			(Start<end &&!) ( Character.isletter (S.charat (start)) | | Character.isdigit (S.charat (start))) start++;
			while (Start<end &&  !) ( Character.isletter (S.charat (end)) | | Character.isdigit (S.charat (end))) end--;
			if (S.charat (start) ==s.charat | | | S.charat (START)-' a ' ==s.charat (end)-' A ' | | S.charat (start)-' a ' = = S.charat (end)-' a ') {
			start++;
			end--;
			} else {break
				;
			}
		}
		if (start>=end) return
			true;
		else {return
			false;
		}
    }

Another One:

public Boolean ispalindrome (String s) {
        if (S.isempty ()) return true;
        int len = S.length ();
        int start = 0;
        int end = len-1;
        while (start<=end) {
        	if (!isalp (S.charat (start)) {
        		start++;
        		Continue;
        	}
        	if (!isalp (S.charat (end)) {
        		end--;
        		Continue;
        	}
        	if (S.charat (start) ==s.charat (end) | | Math.Abs (S.charat (start)-s.charat (end)) ==32) {
        		start++;
				end--;
        	} else return
        		false;
        return true;
    }
	public boolean Isalp (char c) {
		if (c<= ' z ' &&c>= ' a ') | | (c<= ' Z ' &&c>= ' A ') | | (c>= ' 0 ' &&c<= ' 9 '))
			return true;
		else return
			false;
	


C++

BOOL Ispalindrome (string s) {
      if (S.empty ()) return true;
    int len = S.length ();
    int r = len-1;
    int l = 0;
    while (l<=r) {
        if (S[l] >= ' A ' && s[l]<= ' z ') | | (s[l]>= ' A ' && s[l]<= ' Z ') | | (S[l]) >= ' 0 ' && s[l]<= ' 9 ') {
            if ((s[r) >= ' a ' && s[r]<= ' z ') | | (s[r]>= ' A ' && s[r]<= ' Z ') | | (s[r]>= ' 0 ' && s[r]<= ' 9 ')) {
                if (s[l] = = S[r] | | | s[l]-' A ' ==s[r]-' a ' | | s[l]-' a ' = = s[r]-' a ') {
                    l++;
                    r--;
                }
                else return
                    false;
            else{
                r--;
                Continue
            }
        }

        else{
            l++;
            Continue
        }
    }
    return true;
    }




6. Reverse words in a string

Given an input string and reverse the string word by word.

For example,
Given s = "The Sky is Blue",
Return ' Blue is sky '.

Click to show Clarification. Clarification:

What constitutes a word?
A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words?
Reduce them to a single spaces in the reversed string.
Java implementation

public string Reversewords (string s) {
        string newstring = S.trim ();
		if (Newstring.length () <=0) return S.trim ();
		String []splitsstrings = Newstring.split ("");
		int len = splitsstrings.length;
		StringBuilder Sbuilder = new StringBuilder ("");
		for (int i=len-1;i>=0;i--) {
			if (splitsstrings[i].length () >0) {
				sbuilder.append (splitsstrings[i]);
				Sbuilder.append ("");
			}
		}
		String resultstring = sbuilder.tostring ();
		return Resultstring.trim ();
    }
Public String trim ()
Returns a copy of the string, with leading and trailing whitespace omitted.

If This String object is represents an empty character sequence, or the A and last characters of character sequence Sented by thisstring object both have codes greater than ' \u0020 ' (the spaces character), then a reference to Thisstring OB Ject is returned.

Otherwise, if there is no character with a code greater than ' \u0020 ' in the string, then a NewString object representing An empty string is created and returned.

Otherwise, let K being the index of the the "the" the "the", "the", "the" "character", "whose code is greater than ' \u0020 ' Dex of the last character in the string whose the code is greater than ' \u0020 '. A new String object is created, representing the substring of this String so begins with the character in Indexk and end The "s with" character at index M-that are, the result ofthis.substring (k, m+1).

This is used to trim whitespace (as defined above) from the beginning and end of a string. Returns:a copy of this string with leading and trailing white spaces removed, or this string if it has no leading or trail ing white spaces. StringBuilder

Public StringBuilder (String str)
Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is the length of the string argument. Parameters:str-the initial contents of the buffer. Throws:nullpointerexception-if STR is null
C++ Analysis :The clarification is very Important, during the interview, one should of these points without hint, and then the implement.
By checking the clarifications, the programming are straightforward, here provides a simple version which uses buffer Strin GS: (1) Loop from start to the string:(a) If current char is spaces and word string is empty, continue. (b) If current char are space but word string isn't empty, which means we meet the end of word, then output the word, Rese           t the word, continue. (c) If current char are non-space char, add this char to the word string, continue (2) Handle the last Word: (a) If the last word was empty, which means the input is empty, or the input has only spaces, or the last Char/char  s are spaces.       Then just remove the last spaces in the output string and return. (b) If the last word isn't empty, add the last word to the front of the output string, then remove the Output string and return.

void Reversewords (String &s) {
    string word;//tmp string to store all Word
    string res;//result string
    int i = 0;
    for (int i=0;i<s.size (); i++) {
        if (s[i]== ' && word.empty ()) Continue;//multiple spaces
        if (s[i]== ' &&!word.empty ()) {//Word ends
            res = word+ "" +res;//add Word to result string
            Word = "";/Reset the word
            continue;
        }
        if (s[i]!= ') {//non space characters
            Word.push_back (s[i));
            Continue
        }
    }
    if (!word.empty ())//last word
        s = word+ "" +res;
    else
        s = res;
    s = S.substr (0,s.size ()-1);
}




7.

Substring with concatenation of all Words

You are are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of the substring (s) in S-is-a concatenation of each word in L exactly once and without any inte rvening characters.

For example, given:
S: "Barfoothefoobarman"
L: ["foo", "Bar"]

You are should return the indices: [0,9].
(Order does not matter). Analysis : Try to the problem straightforward:
Say in L there are m strings with length n.
What string is required to match in S? A length of m*n string start with each position in S.
What is a match? In the M*n long string, every string in L appear only once.

So the algorithm is:
Scan every M*n long string start from each position in S, "if all" strings in L have been appeared only once USI NG MAP data structure. If So, store the starting position.

Yes, do not consider any DP or DFS solutions, just using the hash map and loop.

Note that L may contain duplicate strings, which require two map

C + + implementation

Vector<int> findsubstring (String S, vector<string> &l) {
        map<string, int> expectCount;
    Map<string, int> Realcount;
    vector<int> result;
    int row = L.size ();
    if (row = = 0) return result;
    int len = (int) l[0].size ();
    for (int i=0; i< l.size (); i++) {
        expectcount[l.at (i)]++;
    }
    for (int i=0; i<= (int) s.size ()-row*len;i++) {
        realcount.clear ();
        int j=0;
        for (; j<row; j + +) {
            string str = S.SUBSTR (I+j*len,len);
            if (Expectcount.find (str)!= expectcount.end ()) {
                realcount[str]++;
            } else{break
                ;
            }
            if (Realcount[str]>expectcount[str]) break
                ;
        if (j = = row)
            result.push_back (i);
    }
    return result;
    }


Java implementation

Public arraylist<integer> findsubstring (String S, string[] L) {arraylist<integer> result = new Arrayl
        Ist<integer> ();
        int num = l.length;
        int eachlen = L[0].length ();
        if (num = = 0 | | Eachlen ==0) return result;
    	hashmap<string, integer> hMap2 = new hashmap<string,integer> ();
			for (int j=0;j<num;j++) {int val = 1;
        		if (Hmap2.containskey (L[j])) {val = Hmap2.get (L[j]);
			val++;
    	} hmap2.put (L[j], Val); for (int i=0;i<=s.length ()-num*eachlen;i++) {hashmap<string, integer> hmap = new Hashmap<str
        	Ing,integer> ();
        	for (int j=0;j<num;j++) {hmap.put (L[j], 0);
        	int k = 0;
        		while (k<num) {String str = s.substring (I+k*eachlen, i+eachlen* (k+1));
        			if (Hmap.containskey (str)) {int val = hmap.get (str);
        			Hmap.put (str, ++val); if (Hmap.get (str) >hmap

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.