String: Finds the first occurrence of a character in a string

Source: Internet
Author: User

Topic:

Finds the first occurrence of a character in a string. If you enter Abaccdeff, then output B.

Ideas:

We can iterate through each character in turn, that is, the number of times each character is asked, and the string is traversed once. But this time complexity is O (n*n).

Consider this, each character corresponds to an ASCII value, we can set an array length of 256, each character ASCII value is the index value of the array. Add one if you encounter the same.

The last traversal of the first occurrence of a character.

Code:

#include <iostream> #include <string>using namespace Std;char firstsingle (string ss) {int count[256]={0}; for (int i=0;i<ss.length (); i++) {count[ss[i]]++;} For (I=0;i<ss.length (); i++) {if (count[ss[i]]==1) return ss[i];}    Return ' & ';} int main () {    string Str;cin>>str;char res;res=firstsingle (str); Cout<<res<<endl;return 0;}

Post

Although this solution is convenient but we consume a lot of space, how can we reduce space? can be considered with bitmap solution. We can think about it.


(Title: Programming Beauty)

String: Finds the first occurrence of a character in a string

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.