Algorithm Analysis
A sentence can end with one of the following punctuation marks: a period, an exclamation mark, or a question mark. At the end of a sentence, there can be several punctuation marks – for example, three dots or three exclamation marks. Therefore, we will track the end of a sentence as follows: the current character must be one of '.', '!', '?', and the previous character must not be. That is, the input text contains as many sentences as there are pairs of adjacent symbols, the second of which belongs to the set {'.', '!', '?'}, and the first does not.
Algorithm Implementation
We read the input data character by character. In the variable cnt
, we count the number of sentences.
prev = cnt = 0; while(scanf("%c",&ch), ch != '\n') { // The variable `ch` contains the current character, and `prev` the previous one. A sentence is considered ended if we reach one of the three punctuation marks, and the previous character is not one of them. if ((ch == '.' || ch == '!' || ch == '?') && !(prev == '.' || prev == '!' || prev == '?')) cnt++; prev = ch; } // We output the number of sentences. printf("%d\n",cnt);
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); String s = con.nextLine(); int cnt = 0; for(int i = 0; i < s.length() - 1; i++) { if ((s.charAt(i+1) == '.' || s.charAt(i+1) == '!' || s.charAt(i+1) == '?') && !(s.charAt(i) == '.' || s.charAt(i) == '!' || s.charAt(i) == '?')) cnt++; } System.out.println(cnt); } }