The first character position that appears only once
- Number of participants: 2802 time limit: 1 seconds space limit: 32768K
- Point of Knowledge: string
- Algorithmic Knowledge Video Tutorial
The title is described in a string (1<= string length <=10000, all composed of letters) to find the position of the first occurrence of a character. If the string is empty, return-1. Position index starting from 0 although the C + + string class used to be super cool, but with the usual habits of use, I prefer remake original C-style characters. I have written two versions of this problem, one is a C + + style string and the other is a C-style. AttentionThe C-style string determines whether to reach the end of the string in two ways:
*p! = ' \ '
*p! = 0
is essentially one thing. string Version:
#include "stdafx.h" #include <string> #include <iostream>using namespace::std;class Solution {Public:int Firstnotrepeatingchar (String str) {if (Str.empty ()) Return-1;int arr[256] = {0};int length = str.length (); for (int i = 0; i < length; i++) {arr[(int) str[i]]++;std::cout << (int) str[i] << Endl;} int retVal = 0;for (int i = 0; i < length; i++) {if (arr[(int) str[i]] = = 1) break;retval++;} if (RetVal = = Str.length ()) {retVal =-1;} return retVal;}; int _tmain (int argc, _tchar* argv[]) {solution s;string test = "ASDFASDFE"; int result = S.firstnotrepeatingchar (test); Retu RN 0;}
C-style string version:
#include "stdafx.h" #include <string> #include <iostream>using namespace::std;class Solution {Public:int Firstnotrepeatingchar (String str) {if (Str.empty ()) return-1;const char* p = str.data (); int strlength = 0;int arr[256] = {0};while (*p! = ') {arr[*p]++;p ++;strlength++;} Const char* P2 = STR.C_STR (); int retVal = 0;while (*p2! = ') ' {if (arr[*p2] = = 1) break;p2++; retval++;} if (RetVal = = strlength) {retVal =-1;} return retVal;}; int _tmain (int argc, _tchar* argv[]) {solution s;string test = "ASDFASDFE"; int result = S.firstnotrepeatingchar (test); Retu RN 0;}
Tell me about the pit inside:string has two functions can go to C-style string, one is C_str (), and the other is data (), the effect seems to be the same, will be at the end of the string "", the key is two functions return value is a const char* pointer
put
Const char* p = str.data ();
Written
char* p = str.data ();
is not a compile-only.
31. The first character position that appears only once